day4 链表part2:交换&倒删&相交
24.两两交换链表中的节点
链表的模拟操作考验coding基本功,画图模拟,想清楚步骤123,注意先后顺序!
/**
* 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) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
// (first, second) 交换成 (second, first)
// 此时的first是下一组(first, second)的pre
ListNode first, second;
while (pre.next != null && pre.next.next != null) {
first = pre.next;
second = first.next;
pre.next = second;
first.next = second.next;
second.next = first;
pre = first;
}
return dummy.next;
}
}
19.删除链表的倒数第 N 个结点
快慢指针的一种用法——快指针先走,快慢指针维持固定距离
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy, fast = dummy;
while (n-- > 0) fast = fast.next;
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}
160.链表相交
两条链表分别走到尾再从另一支开始走到公共节点的距离是一样的
如果没有公共节点,两个指针会同时走到另一支尾部空节点处
两种情况两个指针都会相等,都能跳出循环
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode curA = headA, curB = headB;
while (curA != curB) {
curA = curA == null ? headB : curA.next;
curB = curB == null ? headA : curB.next;
}
return curA;
}
}
142.环形链表 II
快慢指针的另外一种用法——快指针走的比慢指针快,相对速度为1时,一定会相遇(有环情况)
环相交位置与入口位置关系详细数学解释见代码随想录文章 https://programmercarl.com/0142.%E7%8E%AF%E5%BD%A2%E9%93%BE%E8%A1%A8II.html#%E6%80%9D%E8%B7%AF
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null || head.next == null || head.next.next == null)
return null;
ListNode slow = head.next, fast = slow.next;
while (fast != slow) {
// 无环退出
if (fast.next == null || fast.next.next == null) return null;
fast = fast.next.next;
slow = slow.next;
}
// 有环出循环
// fast回到头节点,与slow相同速度移动
fast = head;
while (fast != slow) {
fast = fast.next;
slow = slow.next;
}
return fast;
}
}