相交链表
public class GetIntersectionNode {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> set = new HashSet<>();
while(headA!=null){
set.add(headA);
headA = headA.next;
}
while(headB!=null){
if(set.contains(headB)){
return headB;
}
set.add(headB);
headB=headB.next;
}
return null;
}
}
回文链表
public class IsPalindrome {
private static boolean isPalindrome(ListNode head) {
List<Integer> list = new ArrayList<>();
while(head!=null){
list.add(head.val);
head = head.next;
}
// 下面是双指针法
int l=0;
int r=list.size()-1;
while(l<r){
if(list.get(l)!=list.get(r)){
return false;
}
l++;
r--;
}
return true;
}
删除链表的倒数第 n 个结点
public class RemoveNthFromEnd {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0, head);
ListNode cur = dummy;
int length = getLength(head);
for(int i=1;i<length-n+1;i++){
cur = cur.next;
}
cur.next = cur.next.next;
return dummy.next;
}
public int getLength(ListNode head) {
int length = 0;
while (head != null) {
++length;
head = head.next;
}
return length;
}
}
反转链表
public class ReverseList {
private static ListNode reverseList(ListNode head) {
ListNode cur = head;
ListNode pre = null;
while (cur!=null){
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}
排序链表
public class SortList {
public ListNode sortList(ListNode head) {
ListNode p = head;
int i=0;
int[] arr= new int[50000];
while(p!=null){
arr[i++]=p.val;
p=p.next;
}
Arrays.sort(arr,0,i);
i=0;
p=head;
while(p!=null){
p.val = arr[i++];
p=p.next;
}
return head;
}
}