二叉树之下

带环链表

2018-11-29  本文已影响14人  静水流深ylyang

版权声明:本文为博主原创文章,转载请注明出处。
个人博客地址:https://yangyuanlin.club
欢迎来踩~~~~


Linked List Cycle I

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

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

Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

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

public boolean hasCycle2(ListNode head) {
    if (head == null) {
        return false;
    }
    HashSet<ListNode> set = new HashSet<ListNode>();
    while (head != null) {
        if (set.contains(head)) {
            return true;
        }
        set.add(head);
        head = head.next;
    }
    return false;
}
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
    bool hasCycle(ListNode *head)
    {
        ListNode *fast, *slow;
        fast = slow = head;
        while(fast && fast->next)
        {
            fast = fast -> next -> next;
            slow = slow -> next;
            //快慢指针相遇说明有环
            if(fast == slow)
                return true;
        }
        return false;
    }
};
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
    bool hasCycle(ListNode *head)
    {
        ListNode *fast, *slow;
        fast = slow = head;
        bool isCycle = false;
        while(fast && fast->next)
        {
            fast = fast -> next -> next;
            slow = slow -> next;
            if(fast == slow)
            {
                isCycle = true;
                break;
            }
        }
        if(isCycle)
        {
            fast = head;
            while(fast != slow)
            {
                fast = fast -> next;
                slow = slow -> next;
            }
            return fast;
        }
        return NULL;
    }
};

另外,如果还要求环的长度(最小正周期),由于已经知道了环的起点,只要从它开始遍历,找到第一个等于起点的位置即可,最多还需要O(λ)的时间。


版权声明:本文为博主原创文章,转载请注明出处。 个人博客地址:https://yangyuanlin.club 欢迎来踩~~~~

上一篇 下一篇

猜你喜欢

热点阅读