1. 删除链表的倒数第N个节点
19. 删除链表的倒数第 N 个结点https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
示例1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例2:
输入:head = [1], n = 1
输出:[]
示例3:
输入:head = [1,2], n = 1
输出:[1]
解题思路
通过双指针,两个指针间隔N个,指针到达末尾的时候,就找到了倒数N个。
边界值分析:
存在慢指针并未出发的可能,考虑未出发和已经出发两种情况,尽可能的把两种情况提取出一个一致的动作,所以可以采取虚拟头节点,不论是否出发,都删除慢指针的下一个。
代码
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode preHead = new ListNode();
preHead.next = head;
ListNode slow = preHead, fast = preHead;
for (int i = 0; i < n; i++) {
fast = fast.next;
}
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return preHead.next;
}
}
2. 链表相交
面试题 02.07. 链表相交https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/description/给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
示例 1:
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Intersected at '8'
解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。
在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
解题思路
思考这道题的时候,考虑的是如何能够同时在连接点相遇,然后就可以判断是否是一个节点对象了,所以要考虑的是如何能够一起到达,快慢指针是无法满足的,那就考虑如何能让长的链表先走一部分,所以解法出来了:先遍历一遍,短的到达后,长的继续走的部分就是多的部分。
代码
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int lengA = 0, lengB = 0;
ListNode curA = headA, curB = headB;
while (curA != null) {
curA = curA.next;
lengA++;
}
while (curB != null) {
curB = curB.next;
lengB++;
}
curA = headA;
curB = headB;
if (lengA > lengB) {
for (int i = 0; i < lengA - lengB; i++) {
curA = curA.next;
}
} else {
for (int i = 0; i < lengB - lengA; i++) {
curB = curB.next;
}
}
while (curA != null && curB != null) {
if (curA == curB)
return curA;
else {
curA = curA.next;
curB = curB.next;
}
}
return null;
}
}
3. 环形链表II
142. 环形链表 IIhttps://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
示例1:
输入:head = [3,2,0,-4], pos = 1
输出:返回索引为 1 的链表节点
解释:链表中有一个环,其尾部连接到第二个节点。
示例2:
输入:head = [1,2], pos = 0
输出:返回索引为 0 的链表节点
解释:链表中有一个环,其尾部连接到第一个节点。
示例3:
输入:head = [1], pos = -1
输出:返回 null
解释:链表中没有环。
解题思路
经典的快慢指针寻找环的问题,如果是环状的,快指针迟早套圈遇到慢指针,如果没有环,那么快指针一定先到末尾。
假设环前面X个节点,环有Y个节点,相遇点距离入环点a个节点,fast走了X+nY+a,slow走了X+mY+a,fast是slow的两倍,所以得出:X+a = (n-m)Y。所以,X = (n-m)Y-a,也就是说如果此时从head出发走到入环点,那么从相遇点也同步走,会走到n-m个环后退a个节点,正好是入环点。所以快慢指针相遇后,从head和相遇位置继续同步走,再次相遇就是入环点。
代码
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) {
ListNode index1 = head;
ListNode index2 = fast;
while (index1 != index2) {
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}