## 24. 两两交换链表中的节点

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode() {}
*     ListNode(int val) { this.val = val; }
*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
ListNode dummy = new ListNode(-1, head);
ListNode cur = dummy;
while(cur.next != null && cur.next.next != null){
ListNode tmp = cur.next;
ListNode tmp1 = cur.next.next.next;

cur.next = cur.next.next;
cur.next.next = tmp;
cur.next.next.next = tmp1;

cur = cur.next.next;
}
return dummy.next;
}
}``````

## 19.删除链表的倒数第N个节点

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode() {}
*     ListNode(int val) { this.val = val; }
*     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pre = dummy;
for(int i = 0; i < n; i++){
cur = cur.next;
}
while(cur != null){
pre = pre.next;
cur = cur.next;
}
pre.next = pre.next.next;
return dummy.next;
}
}``````

## 面试题 02.07. 链表相交

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
int lenA = 0;
int lenB = 0;
while(cura != null){
lenA++;
cura = cura.next;
}
while(curb != null){
lenB++;
curb = curb.next;
}

if(lenA > lenB){
int n = lenA-lenB;
while(n-- > 0){
}
}
}
return null;
}else{
int n = lenB-lenA;
while(n-- > 0){
}
}
}
return null;
}

}
}``````

## 142.环形链表II

slow移动 （x+z）， fast 移动 x+z+n(y+z)，以及 2(x+z) = x+z+n(y+z) => x = (n-1)(y+z)+y ， 其中n表示fast指针在环内绕的圈数，把n-1的环内距离抵消掉的话，就可以推导出x = y，放两个指针同时出发，相遇的地方就是入口

``````/**
* class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
//快慢指针，快指针比慢指针快两步，这样如果存在环，快慢指针一定会相遇
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){    //确定有环
ListNode index2 = fast;
while(index1 != index2){
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}``````