Leetcode Linked List Cycle ,本算法主要检测单链表中的环,算法要求O(1)的空间。本算法通过以不同的步长进行检测,如果步长大于环长,则一定可以验测到环,算法时间复杂度O(n),相关代码如下:
#include<iostream>
#include<vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/*
* Each step we traves 2^k element in the linked list, if there is a node
* equals to the anchor node, there is a cycle in the linked list.
* And the time spend is O(2n), and space spend is O(1).
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head) {
return false;
}
int inc = 1;
ListNode* anchor = head;
ListNode* cur = head->next == NULL? NULL: head->next;
while (cur) {
anchor = cur;
// Scan the list find the equals one
for (int i = 0; i < inc && cur; i ++) {
cur = cur->next;
if (cur == anchor) {
return true;
}
}
inc *= 2;
}
return false;
}
};
// 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;
bool re = so.hasCycle(head);
cout<<"resutl: "<<re<<endl;
return 0;
}