Leetcode Linked List Cycle II

Leetcode Linked List Cycle II ,本算法检测环的开始的点,基于Linked List Cycle 的结果,如果环存在,记录环长为cycleLength,并使用相隔cycleLength的两个游标进行遍历,则第一次两游标相等的时候,即为环的开始,相关代码如下:

#include<iostream>
#include<vector>

using namespace std;
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
/*
 * We find the length of the cycle firstly, if the cycle exsit. And then, we
 * use two cursors which intercept with length-1 node to scan the linked list.
 * The first time that the two cursor equally is the begin of the cycle.
 */
class Solution {
public:
    ListNode* detectCycle(ListNode *head) {
        if (!head) {
            return head;
        }
        int inc = 1;
        int cycleLength = 0;
        ListNode* anchor = head;
        ListNode* cur = head->next == NULL? NULL: head->next;
        bool exist = false;
        // Get the length of the cycle, if it exist.
        while (cur && !exist) {
            anchor = cur;
            for (int i = 0; i < inc && cur; i ++) {
                cur = cur->next;
                if (cur == anchor) {
                    cycleLength = i;
                    exist = true;
                    break;
                }
            }
            inc *= 2;
        }
        // Use cursor scan the two cursor.
        if (exist) {
            anchor = head;
            cur = head;
            for (int i = 0; i <= cycleLength; i ++) {
                cur = cur->next;
            }
            while (cur != anchor) {
                cur = cur->next;
                anchor = anchor->next;
            }
            return anchor;
        } else {
            return NULL;
        }
    }
};

// Sample input: ./a.out argv1 argv2 ...
int main(int argc, char* argv[]) {
    Solution so;
    vector<string> test;
    ListNode* head = NULL;
    ListNode* cur = NULL;
    // Make the test linked list
    for (int i = 1; i < argc; i ++) {
        if (cur) {
            cur->next = new ListNode(atoi(argv[i]));
            cur = cur->next;
        } else {
            cur = new ListNode(atoi(argv[i]));
            head = cur;
        }
    }
    cur->next = head;
    head = so.detectCycle(head);
    if (head) {
        cout<<"resutl: "<<head->val<<endl;
    } else {
        cout<<"resutl: NULL"<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值