#102 Linked List Cycle

来源:互联网 发布:php global用法 编辑:程序博客网 时间:2024/06/03 06:38

题目描述:

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


Example

Given -21->10->4->5, tail connects to node index 1, return true

Challenge 

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

题目思路:

这是一题挺有名的龟兔赛跑问题。设两个pointer,一个slow每次走一格,一个fast每次走2格。如果有circle,那么slow和fast必会在circle中的某一点相遇。否则就没有circle。

Mycode(AC = 23ms):

/** * Definition of ListNode * class ListNode { * public: *     int val; *     ListNode *next; *     ListNode(int val) { *         this->val = val; *         this->next = NULL; *     } * } */class Solution {public:    /**     * @param head: The first node of linked list.     * @return: True if it has a cycle, or false     */    bool hasCycle(ListNode *head) {        // write your code here        if (head == NULL || head->next == NULL) {            return false;        }                ListNode *slow = head, *fast = head;        while (fast && fast->next && fast->next->next) {            slow = slow->next;            fast = fast->next->next;                        if (slow->val == fast->val) {                return true;            }        }                return false;    }};


0 0
原创粉丝点击