lintcode 带环链表

lintcode 带环链表

描述

给定一个链表,判断它是否有环。

样例

给出 -21->10->4->5, tail connects to node index 1,返回 true

挑战

不要使用额外空间

思路

快慢指针,如果有环,一定能在On时间内相遇。

代码

/**
 * Definition of singly-linked-list:
 * 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 || !head->next) return false;
        ListNode *fast = head->next->next, *slow = head;
        while (fast && fast->next) {
            if (fast == slow && fast != NULL)
                return true;
            fast = fast->next->next;
            slow = slow->next;
        }
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_40147449/article/details/87541922