Saturday, September 20, 2014

LeetCode: 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?


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 
     typedef ListNode ln;

ListNode *detectCycle(ListNode *head) { if(!head || !head->next)return NULL; ln *fast = head, *slow = head; while(fast && fast->next) { slow = slow->next; fast = fast->next->next; if(fast == slow)break; } if(fast != slow)return NULL; ln *first = head, *second = slow; while(first != second) { first = first->next; second = second->next; } return first; }

No comments:

Post a Comment