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;
}
};