LeetCode OJ Linked List Cycle

来源:互联网 发布:淘宝网店在哪里看 编辑:程序博客网 时间:2024/06/16 03:31

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

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

to solve this problem is quiet easy but ingenious. Declare two pointers whose speed is twice as fast as another. When there 2 pointers are meet, there is a loop in the list.
Prove:

Suppose the 2 pointers meet after t time, which means t times movement. Then the difference is 2t - t = t, which is surely the loop's length. Notice that t will increase from 0 to max_length(the length of the list), if there is a loop in the list, we can find it.

class Solution {public:    bool hasCycle(ListNode *head) {        ListNode *temp_1 = head;        ListNode *temp_2 = head;        while (temp_2 != NULL && temp_2->next != NULL) {            temp_1 = temp_1->next;            temp_2 = temp_2->next->next;            if (temp_1 == temp_2) {                return true;            }        }        return false;    }};


0 0
原创粉丝点击