leetcode 024
public static ListNode swapPairs(ListNode head) {
ListNode head1= new ListNode(0);
head1.next =head;
if(head1.next==null) return null;
if(head1.next.next==null) return head1.next;
ListNode cur = head1;
ListNode post = head1.next;
ListNode last = head1.next.next;
ListNode end = last.next;
while(cur.next!=null && cur.next.next!=null) {
cur.next = last;
last.next = post;
post.next = end;
cur = cur.next.next;
post = cur.next;
if(post!=null) last = cur.next.next;
if(last!=null) end = last.next;
}
return head1.next;
}
leetcode 19
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode head1= new ListNode(0);
head1.next=head;
ListNode cur = head1;
//快指针先跑到 第n-1个节点
for(int i=0;i<n;i++){
cur = cur.next;
}
ListNode slow = head1;
while(cur.next!=null){
slow=slow.next;
cur=cur.next;
}
// delete
slow.next = slow.next.next;
return head.next;
}
leetcode 02-07
public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int len1=0;
int len2=0;
ListNode cur1= headA;
ListNode cur2 = headB;
while(cur1!=null){
len1++;
cur1 = cur1.next;
}
while(cur2!=null){
len2++;
cur2=cur2.next;
}
int m=abs(len1-len2);
if(len1 < len2){
cur1= headB;
cur2= headA;
}else {
cur1=headA;
cur2=headB;
}
for(int i=0;i<m;i++){
cur1=cur1.next;
}
while(cur2!=null){
if(cur1==cur2) {
break;
}
cur2=cur2.next;
cur1=cur1.next;
}
return cur2;
}
leetcode 142
public static ListNode detectCycle(ListNode head){
ListNode fast=head;
ListNode slow=head;
if(head==null || head.next==null) return null;
//fast = head.next;
//相遇节点
while( fast!=null && fast.next!=null){
slow = slow.next;
fast = fast.next.next;
if(slow==fast){
//环的入口
ListNode index1= head;
ListNode index2= fast; //or meetNode;
while(index1!=index2){
index1=index1.next;
index2=index2.next;
}
ListNode entryNode= index1;
ListNode meetNode = fast;
//return meetNode;
return entryNode;
}
}
return null;
}