Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594

[LeetCode]Linked List Cycle [& II]-2014.01.06

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

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理