总结一下思路:
1. 设置快慢指针,一个走一步,一个走两步。
2. 相遇时慢指针回到链表初始位置
3. 两个指针此时个走一步,一直循环到相遇
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if (fast == slow){
slow = head;
while (fast != slow){
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
return null;
}
}
第一次看题目感觉很懵,不知道是要我干嘛。。。
1. 遍历两个链表,得出长度后回到链表开始的位置
2. 算出差值,哪个链表长,哪个就从开始位置先走相差的步数
3. 遍历两个链表,直到节点地址相等时return
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode curA = headA;
ListNode curB = headB;
int numA = 0;
int numB = 0;
while (curA != null){
curA = curA.next;
numA++;
}
while (curB != null) {
curB = curB.next;
numB++;
}
int gap;
if (numA > numB) {
gap = numA - numB;
while (gap != 0){
headA = headA.next;
gap--;
}
while (headA != headB){
headA = headA.next;
headB = headB.next;
}
return headA;
} else {
gap = numB - numA;
while (gap != 0){
headB = headB.next;
gap--;
}
while (headB != headA){
headA = headA.next;
headB = headB.next;
}
return headA;
}
}
}
/**
* Definition for singly-linked list.
* 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 dummy = new ListNode(0, head);
ListNode fast = head;
ListNode slow = dummy;
// 找到n-1位置的node
for (int i=0; i<n ; i++){
fast = fast.next;
}
//
while (fast != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
总结一下需要注意有头节点的操作,所以我用了dummyHead
/**
* Definition for singly-linked list.
* 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 swapPairs(ListNode head) {
if (head == null) {
return null;
}
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode cur = dummyHead;
while (cur.next != null && cur.next.next != null) {
ListNode temp = cur.next;
ListNode temp2 = cur.next.next.next;
cur.next = cur.next.next;
cur.next.next = temp;
cur.next.next.next = temp2;
cur = cur.next.next;
}
return dummyHead.next;
}
}