LeetCode之旅(33)

来源:互联网 发布:apl美皇公司知乎 编辑:程序博客网 时间:2024/06/06 03:52

Linked List Cycle II


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

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


参考了一篇博客:http://www.cnblogs.com/x1957/p/3406448.html


/** * 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) {        if (!head) return NULL;        ListNode *slow = head, *fast = head;        while (fast) {            if (fast) fast = fast->next;            if (fast) fast = fast->next;            if (slow) slow = slow->next;            if (fast && fast==slow) {                slow = head;                while (slow != fast)                    fast = fast->next, slow = slow->next;                return slow;            }        }        return NULL;    }};


0 0
原创粉丝点击