首页 > 其他 > 详细

LeetCode -- Linked List Cycle

时间:2014-05-20 01:40:45      阅读:390      评论:0      收藏:0      [点我收藏+]

题目链接

题意: 给出单链表, 判断是否存在环.

方法就是大步小步...

附上代码:

bubuko.com,布布扣
 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         if (head == NULL or head->next == NULL) {
13             return false;
14         }
15         ListNode *fast = head, *slow = head;
16         while (fast != NULL and fast->next != NULL) {
17             fast = fast->next;
18             if (fast == slow) {
19                 return true;
20             }
21             fast = fast->next;
22             if (fast == slow) { 
23                 return true;
24             }
25             slow = slow->next;
26         }
27         return false;
28     }
29 };
bubuko.com,布布扣

 

 

LeetCode -- Linked List Cycle,布布扣,bubuko.com

LeetCode -- Linked List Cycle

原文:http://www.cnblogs.com/Stomach-ache/p/3731125.html

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