首页 > 其他 > 详细

141. Linked List Cycle

时间:2017-04-23 12:20:41      阅读:188      评论:0      收藏:0      [点我收藏+]

题目:

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!