leetcode: Linked List Cycle

http://oj.leetcode.com/problems/linked-list-cycle/

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         if (NULL == head) {
 5             return false;
 6         }
 7         
 8         ListNode *curr = head, *next = head->next;
 9         
10         while (true) {
11             curr = curr->next;
12             
13             int steps = 0;
14             
15             while ((next != NULL) && (steps < 2)) {
16                 next = next->next;
17                 ++steps;
18             }
19             
20             if (NULL == next) {
21                 return false;
22             }
23             
24             if (curr == next) {
25                 return true;
26             }
27         }
28     }
29 };

 

posted @ 2013-10-31 17:58  移山测试工作室黑灯老师  阅读(207)  评论(0编辑  收藏  举报
count website visits
Buy Computers