码迷,mamicode.com
首页 > 其他好文 > 详细

141. Linked List Cycle

时间:2017-04-23 12:34:10      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:class   sed   ast   fast   log   ide   ==   for   题目   

题目:

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

思路:

设置一个快指针,一个慢指针。快指针的步长为2,慢指针的步长为1。快指针和慢指针终会进入环中并在环中循环,最终相遇。

判断条件:需要判断快慢指针是否为NULL,以及快指针指向的下一个节点是否为空。

代码:

技术分享
 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 *fast = head;
13         ListNode *slow = head;
14         while ((fast != NULL) && (slow != NULL) && (fast->next != NULL)) {
15             fast = fast->next->next;
16             slow = slow->next;
17             if (fast == slow) {
18                 return true;
19             }
20         }
21         return false;
22     }
23 };
View Code

 

141. Linked List Cycle

标签:class   sed   ast   fast   log   ide   ==   for   题目   

原文地址:http://www.cnblogs.com/sindy/p/6752096.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!