-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFirst_element_of_loop_LinkedList
More file actions
50 lines (44 loc) · 1.02 KB
/
First_element_of_loop_LinkedList
File metadata and controls
50 lines (44 loc) · 1.02 KB
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
// Find first element of loop in linked list
// C++
#include <iostream>
using namespace std;
struct Node {
int data;
Node *next;
Node(int d=0): data(d), next(nullptr){}
};
Node* fist_node_loop(Node* head){
if(!head || !head->next) return nullptr;
Node *slow = head;
Node *fast = head;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast) //--> loop
break;
}
if(slow != fast )
return nullptr;
slow = head;
while(slow != fast){
slow = slow->next;
fast = fast->next;
}
return fast;
}
// 1->2->3->4->5->6->NULL
int main(){
Node n1(1), n2(2), n3(3), n4(4), n5(5), n6(6), n7(7), n8(8);
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = &n5;
n5.next = &n6;
n6.next = &n7;
n7.next = &n8;
n8.next = &n3;
//TODO:
Node* first_node = fist_node_loop(&n1);
if (first_node) cout << first_node->data << endl;
else cout << "No loop" << endl;
}