[leetcode141142]Linked List Cycle I II

来源:互联网 发布:做网络推广职业前景 编辑:程序博客网 时间:2024/06/09 19:14

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

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

如何求环的长度,记住碰撞点的指针,让slow指针不停向后遍历,当再次回到碰撞点时走过的距离就是环的长度。

碰撞点到环节点 = 头结点到环节点

设环外长度为a,环长度为r,碰撞点距离环节点为b。

有a+b = s; a+b+nr = 2s;

s = nr;

i<a 时 t(i)= i;

i>=a时,t(i)=a+(i-a)%r

t(a) = t(nr+a)=t(s+a)

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    bool hasCycle(ListNode *head) {        ListNode *slow = head;        ListNode *fast = head;        while(NULL != fast && NULL != fast->next) //can divide only one node that have cycle or don't have cycle        {            slow = slow->next;            fast = fast->next->next;            if(slow == fast){return true;}        }        return false;    }};

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?

class Solution {public:    ListNode *detectCycle(ListNode *head) {        ListNode *slow = head;        ListNode *fast = head;        ListNode *find = head;        while(NULL != fast && NULL != fast->next) //can divide only one node that have cycle or don't have cycle        {            slow = slow->next;            fast = fast->next->next;            if(slow == fast)            {                while(slow != find)                {                    slow = slow->next;                    find = find->next;                }                return find;            }        }        return NULL;    }};




0 0
原创粉丝点击