【Leetcode】142. Linked List Cycle II总结
小虾米
阅读:507
2022-03-12 16:24:25
评论:0
本文章主要介绍了【Leetcode】142. Linked List Cycle II,具有不错的的参考价值,希望对您有所帮助,如解说有误或未考虑完全的地方,请您留言指出,谢谢!
142. Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
思路
首先证明链表有环,再让一个指针从头开始,另一个指针从相遇的位置,每次都只走一步,相遇的地方就是链表的环开始的地方。
代码
public ListNode detectCycle(ListNode head) {
if (head == null) return null;
boolean flag = false;
ListNode fast = head, slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
flag = true;
break;
}
}
if (!flag) return null;
slow = head;
while (true) {
//先判断,避免只有两个节点的环的情况
if (slow == fast) return slow;
slow = slow.next;
fast = fast.next;
}
}
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。