[LeetCode] Linked List Cycle

A classic interview question of linked list. The idea is to maintain two pointers, one move one step at a time and the other move two steps at a time. If they become the same, a cycle exists. Otherwise, they will become NULL finally and there is no cycle.

The code is as follows.

 1     bool hasCycle(ListNode *head) {
 2         ListNode* slow = head;
 3         ListNode* fast = head;
 4         while (fast && fast -> next) {
 5             slow = slow -> next;
 6             fast = fast -> next -> next;
 7             if (slow == fast) return true;
 8         }
 9         return false;
10     }
posted @ 2015-06-08 22:06  jianchao-li  阅读(157)  评论(0编辑  收藏  举报