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; }
相关文章推荐
- [C/C++]反转链表
- 动易2006序列号破解算法公布
- Flex Namespace的用法
- C#实现基于链表的内存记事本实例
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析