Posted on 2014-01-11 02:09
Uriel 阅读(110)
评论(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 };