Leetcode--142. 环形链表Ⅱ
給定一個鏈表,返回鏈表開始入環的第一個節點。?如果鏈表無環,則返回?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
解釋:鏈表中沒有環。
思路:從環形鏈表那道題來看,當兩個指針在環內相遇時,快指針比慢指針多走了n步,設環周長為k
則n%k==0
慢指針總共走了n步,設環外的長度為m,則它在環內走了n-m步,因此它再走m步就到達了環的入口處
所以我們讓一個指針從起點開始走,當它與慢指針相遇時,它們都走了m步,相遇的地點就是入口
提交的代碼:
/**
?* Definition for singly-linked list.
?* class ListNode {
?* ? ? int val;
?* ? ? ListNode next;
?* ? ? ListNode(int x) {
?* ? ? ? ? val = x;
?* ? ? ? ? next = null;
?* ? ? }
?* }
?*/
public class Solution {
? ? public ListNode detectCycle(ListNode head) {
? ? ? ? ?if(head==null||head.next==null)
? ? ? ? {
? ? ? ? ? ? return null;
? ? ? ? }
? ? ? ? ListNode slow,fast;
? ? ? ? slow = head;
? ? ? ? fast = head.next;
? ? ? ? while(slow!=fast)
? ? ? ? {
? ? ? ? ? ? if(fast.next==null||fast.next.next==null)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? return null;
? ? ? ? ? ? }
? ? ? ? ? ? slow = slow.next;
? ? ? ? ? ? fast = fast.next.next;
? ? ? ? }
? ? ? ? slow = slow.next;
? ? ? ?// System.out.println(head.val);
? ? ? ? fast = head;
? ? ? ? while(fast!=slow)
? ? ? ? {
? ? ? ? ? ? fast = fast.next;
? ? ? ? ? ? slow = slow.next;
? ? ? ? ? ?// System.out.println(fast.val+" ?"+slow.val);
? ? ? ? }
? ? ? ? return fast;
? ? }
}
總結
以上是生活随笔為你收集整理的Leetcode--142. 环形链表Ⅱ的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode--102. 二叉树的层
- 下一篇: 多线程-线程同步