代码改变世界

leetcode - Linked List Cycle

2013-10-31 14:59  张汉生  阅读(154)  评论(0编辑  收藏  举报

 

 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         // IMPORTANT: Please reset any member data you declared, as
13         // the same Solution instance will be reused for each test case.
14         ListNode * itr = head;
15         int n = 1;
16         while (true){
17             if (itr==NULL)
18                 return false;
19             ListNode * tmp = itr;
20             for (int i=0; i<n; i++){
21                 tmp = tmp->next;
22                 if (tmp==NULL)
23                     return false;
24                 else if (tmp == itr)
25                     return true;
26             }
27             n++;
28             itr = itr->next;
29         }
30         return false;
31     }
32 };