lintcode帶環鏈表

帶環鏈表 

給定一個鏈表,判斷它是否有環。

樣例

給出 -21->10->4->5, tail connects to node index 1,返回 true

挑戰 

不要使用額外的空間

用兩個指針,分別表示快慢,如果有循環的話總會相遇的
這裏多說一下,快指針追慢指針,最多也就在慢指針走到一圈就相遇了(不論快指針比慢指針快多少步),因爲慢指針與快指針之間的差值(快指針朝慢指針方向)爲環形的長度減1(這裏考慮的情況爲快指針比慢指針每次多走一步),快指針每走一步與慢指針的相對距離減少1,那麼最多走環形的長度減1步
/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */


class Solution {
public:
    /*
     * @param head: The first node of linked list.
     * @return: True if it has a cycle, or false
     */
    bool hasCycle(ListNode * head) {
        // write your code here
        ListNode *fast=head,*slow=head;
        while(fast&&fast->next)
        {
            fast=fast->next->next;
            slow=slow->next;
            if(slow==fast)
            return true;
        }
        return false;
    }
};

這裏還有個求環形入口的問題,日後有時間再整理
發佈了88 篇原創文章 · 獲贊 28 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章