-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path142_linked_list_cycle_2.cpp
63 lines (55 loc) · 1.24 KB
/
142_linked_list_cycle_2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include "listNode.hpp"
#include <iostream>
#include <list>
#include <vector>
#include <array>
#include <set>
#include <unordered_map>
#include <prettyprint.hpp>
using namespace std;
/*
class ListNode
{
public:
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
*/
// Algorightm: double pointer
ListNode *detectCycle(ListNode *head)
{
if(head == NULL) return NULL;
ListNode *first = head;
ListNode *second = head;
while(second) {
first = first->next;
second = second->next;
if(second == NULL) return NULL;
second = second->next;
if(first == second) break;
}
if(second== NULL) return NULL;
std::cout<<"current P:"<<second->val<<std::endl;
first = head;
//second = second->next;
while(first != second) {
first = first->next;
second = second->next;
}
return first;
}
TEST_CASE("", "")
{
list<int> list1{1,2,3,4};
ListNode *head1 = loadListNode(list1);
REQUIRE(!detectCycle(head1));
ListNode *p1 = head1->next;
ListNode *p2 = head1->next->next->next;
p2->next = p1;
REQUIRE(detectCycle(head1));
ListNode *pNULL = NULL;
REQUIRE(!detectCycle(pNULL));
}