leetcode 141|142. Linked List Cycle 1|2

来源:互联网 发布:mac地址查询厂商设备 编辑:程序博客网 时间:2024/06/06 04:05

141. Linked List Cycle

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

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

思路就是两个指针p,q
p一次走一步
q一次走两步
如果还能相等,就说明有个环

/** * 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(fast && fast->next)        {            slow = slow->next;            fast = fast->next->next;            if (slow ==fast)                return 1;        }        return 0;         }};


142. Linked List Cycle II

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

Note: Do not modify the linked list.

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

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *detectCycle(ListNode *head)     {        ListNode *slow = head;        ListNode *fast = head;               while(fast && fast->next)        {            slow = slow->next;            fast = fast->next->next;            if (fast == slow)            {                slow = head;                while (slow != fast)                {                    slow = slow->next;                    fast = fast->next;                }                return fast;            }        }        return NULL;        }};




原创粉丝点击