Leetcode142. 环形链表 II
题目:
相似题目:Leetcode141. 环形链表
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
说明:不允许修改给定的链表。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。

示例 2:
输入:head = [1,2], pos = 0
输出:tail connects to node index 0
解释:链表中有一个环,其尾部连接到第一个节点。

示例 3:
输入:head = [1], pos = -1
输出:no cycle
解释:链表中没有环。

进阶:
你是否可以不用额外空间解决此题?
题解:
1.定义两个指针,快指针每次走两步,慢指针每次走一步;
2.根据快慢判断链表是否有环,如果无环,返回null,如果有环,返回快慢指针相交的链表节点;
3.定义两个指针,一个指向原始链表头结点,一个指向快慢指针相交的节点,同时移动两个指针,当两个指针相等时,刚好是相交的节点。
java代码:
public static ListNode detectCycle2(ListNode head) {
ListNode slow =head;
ListNode fast=head;
while(fast!=null && fast.next!=null){
fast =fast.next.next;
slow=slow.next;
if(slow==fast){
ListNode pre =head;
while(pre!=slow){
pre =pre.next;
slow =slow.next;
}
return pre;
}
}
return null;
}
/**
* @param head
* @return
*/
public static ListNode detectCycle(ListNode head) {
if (head == null) return null;
ListNode interNode = isNotCycle(head);
if (interNode == null) return null;
ListNode pt1 = head;
ListNode pt2 = interNode;
while (pt1 != pt2) {
pt1 = pt1.next;
pt2 = pt2.next;
}
return pt1;
}
/**
* 判断链表是否有环
*
* @param head
* @return
*/
public static ListNode isNotCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) return slow;
}
return null;
}
本文详细解析了LeetCode142题环形链表II的解决方案,通过快慢指针判断链表是否存在环,并定位环的起始节点。提供了Java代码实现,适用于希望深入了解链表操作及算法优化的读者。
1489

被折叠的 条评论
为什么被折叠?



