lintcode-103-带环链表 II

带环链表 II

给定一个链表,如果链表中存在环,则返回到链表中环的起始节点的值,如果没有环,返回null。

样例

给出 -21->10->4->5, tail connects to node index 1,返回10

挑战

不使用额外的空间

标签

链表 两根指针

思路

参考lintcode-102-带环链表
首先,利用快慢指针判断有无环,若遇到slow == fast时,存在环,跳出循环;
然后,使fast=head,slow不变,slow与fast同步移动,直至再次相遇,即是链表中环的起始节点。

code

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: The node where the cycle begins. 
     *           if there is no cycle, return null
     */
    ListNode *detectCycle(ListNode *head) {
        // write your code here
        ListNode * fast = head, *slow = head, *result = NULL;

        while(fast != NULL && fast->next != NULL) {
            slow = slow->next;
            fast = fast->next->next;

            if(fast == slow) {
                break;
            }
        }
        
        if(fast != NULL && fast->next != NULL) {
            fast = head;
            while(fast != slow) {
                slow = slow->next;
                fast = fast->next;
            }
            result = fast;
        }
        return result;
    }
};
posted @ 2017-07-14 09:14  LiBaoquan  阅读(310)  评论(0编辑  收藏  举报