-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLinkedList.cpp
More file actions
79 lines (64 loc) · 1.31 KB
/
LinkedList.cpp
File metadata and controls
79 lines (64 loc) · 1.31 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include<iostream>
using namespace std;
struct Node{
int data;
struct Node * next;
} ;
struct Node *head = NULL;
struct Node * addNode(int val){
if(head ==NULL){
head = new struct Node;
head->data = val;
head->next = NULL; // Represents end of LL
return head;
}
struct Node * temp = head;
while(temp->next != NULL){
temp = temp -> next;
}
temp -> next = new struct Node;
temp -> next->data = val;
temp -> next->next = NULL; // Represents end of LL
return temp -> next ;
}
void print(){
struct Node * temp = head;
while(temp != NULL){
cout<< temp->data <<"->"<<endl;
temp = temp -> next;
}
}
int sizeLL(){
int count = 0;
struct Node * temp = head;
while(temp != NULL){
count++;
temp = temp -> next;
}
return count;
}
int main()
{
addNode(1);
addNode(2);
addNode(3);
struct Node * first = addNode(4);
addNode(5);
addNode(6);
addNode(7);
struct Node * second = addNode(8);
second->next = first;
struct Node *slow = head, *fast = head;
bool loopExist = false;
while( slow && fast && fast -> next ){
slow = slow -> next;
fast = fast -> next -> next;
if(slow == fast ){
//There is a cycle!
loopExist = true;
break;
}
}
cout<<"Loop Exist : "<<loopExist<<endl;
return 0;
}