[leetcode] 141. Linked List Cycle

Question:

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

Solution:

很有趣的一道題。要求使用O(1)的空間複雜度。主要思路是對於訪問過的節點,都把指向下一個節點的指針指向head,然後跳到原本的下一個節點繼續訪問。這樣,如果有環,就會在某個時刻跳回到一個已訪問的節點,然後訪問該節點的下一個節點,就會訪問到head,於是檢測到右環。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (!head || !head->next)
            return false;
        ListNode *tmp = head->next, *t;
        while (tmp) {
            if (tmp == head)
                return true;
            t = tmp->next;
            tmp->next = head;
            tmp = t;
        }
        return false;
    }
};
發佈了79 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章