標籤:style blog color io for div 問題 log sp
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up:
Can you solve it without using extra space?
題目意思很簡單,判斷鏈表是否有環,若有,返迴環的位置。
一開始,用了原來I的方法,結果會出現逾時。
public ListNode detectCycle(ListNode head) { boolean iscycle=false; if (head!=null) { ListNode temp=head; while (!iscycle) { head=head.next; temp.next=temp; temp=head; if (head==null) { return null; }else { if (head.next==head) { return head; } } } } return head; }
後來發現,我這個演算法必須遍曆完鏈表。
查看了網上其他方法。如下演算法:
對於判斷鏈表是否有環,方法很簡單,用兩個指標,一開始都指向頭結點,一個是快指標,一次走兩步,一個是慢指標,一次只走一步,當兩個指標重合時表示存在環了。
證明:假設鏈表有環,環的長度為N,慢指標在起始位置,快指標在位置k(位置從0開始計數),那麼快指標只要比慢指標多走經過N-k步,就可以追上慢指標了。。。,因為每一次快指標都比慢指標多走一步,所以一定可以在有限的步數追上慢指標。
成功ac。
/** * 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) { ListNode node = null; if(head == null) return node; ListNode quick = head; ListNode slow = head; boolean tag = false; while(quick!=null &&quick.next != null) { quick = quick.next; quick = quick.next; slow = slow.next; if(quick == slow) { tag = true; break; } } if( tag == false) { return node; } else { quick = head; while( true) { if( quick == slow) { return quick; } else { quick = quick.next; slow = slow.next; } } } }}
LeetCode Linked List Cycle II 逾時問題