1. 程式人生 > >LeetCode 141. Linked List Cycle

LeetCode 141. Linked List Cycle

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

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

題意:檢視一個連結串列是否存在圈,不使用額外的空間
分析:不使用額外的空間意味著空間複雜度為O(1)
解題思路看程式碼:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class
Solution {
public: /* 這個題我開始寫超時了,原因我沒有考慮部分圈的情況 整個圈:1 -> 2 -> 3 -> 1 部分圈:1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 4 看討論發現有個好辦法就是使用兩枚指標,一枚指標每次移動1步,另一枚每次移動2步 如果有圈,兩枚指標終有一刻會相遇 如果沒有圈,移動得快的那一枚就會遇到NULL */ bool hasCycle(ListNode *head) { if
(head == NULL || head -> next == NULL) return false; ListNode *oneStep = head, *twoStep = head; while(twoStep -> next != NULL && twoStep -> next -> next != NULL){ oneStep = oneStep -> next; // 每次移動一步 twoStep = twoStep -> next ->
next; // 每次移動兩步 if(oneStep == twoStep) // 相遇代表存在圈 return true; } return false; // 遇到了NULL } };