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

LeetCode OJ:Linked List Cycle(链表循环)

时间:2015-11-04 00:32:06      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:

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

Follow up:
Can you solve it without using extra space?

判断一个链表是否存在环,维护快慢指针就可以,如果有环那么快指针一定会追上慢指针,代码如下:

 1 class Solution {
 2 public:
 3     bool hasCycle(ListNode *head) {
 4         ListNode * slow, * fast;
 5         slow = fast = head;
 6         while(slow && fast){
 7             slow = slow->next;
 8             fast = fast->next;
 9             if(fast) fast = fast->next;
10             if(fast && slow && slow == fast)
11                 return true;
12         }
13         return false;
14     }
15 };

 

LeetCode OJ:Linked List Cycle(链表循环)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4934642.html

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