Posted on 2014-01-11 02:09
Uriel 閱讀(114)
評論(0) 編輯 收藏 引用 所屬分類:
LeetCode
太弱想不出來,參考了解題報告:
http://blog.csdn.net/sysucph/article/details/15378043
挫代碼:
Linked List Cycle
1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 bool hasCycle(ListNode *head) {
12 ListNode *slow = head, *fast = head;
13 while(fast && fast->next) {
14 slow = slow->next;
15 fast = fast->next->next;
16 if(slow == fast) break;
17 }
18 if(fast == NULL || fast->next == NULL) return false;
19 return true;
20 }
21 };
Linked List Cycle II
1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 bool hasCycle(ListNode *head) {
12 ListNode *slow = head, *fast = head;
13 while(fast && fast->next) {
14 slow = slow->next;
15 fast = fast->next->next;
16 if(slow == fast) break;
17 }
18 if(fast == NULL || fast->next == NULL) return false;
19 return true;
20 }
21 };