您的位置:首页 > 其它

Leetcode Linked List Cycle II

2015-11-16 22:13 411 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 namespace 链表