-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfloydCycle.cpp
138 lines (133 loc) · 2.47 KB
/
floydCycle.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include<iostream>
using namespace std;
class node{
public:
int data;
node*next;
node(int d){
data=d;
node*next= NULL;
}
};
//Passing a pointer variable by reference
void insertAtHead(node*&head, int data){
node*n= new node(data);
n->next = head;
head= n;
}
int length(node*head){
int len=0;
while(head!=NULL){
head= head->next;
len+=1;
}
return len;
}
void insertAtTail(node*&head, int data){
if(head==NULL){
head= new node(data);
return;
}
node*tail=head;
while(tail->next!=NULL){
tail= tail->next;
}
tail->next= new node(data);
return;
}
void insertAtMiddle(node*&head, int data, int p)
{
if(head==NULL || p==0){
insertAtHead(head,data);
}
else if(p>length(head)){
insertAtTail(head,data);
}
else{
int jump=1;
node*temp= head;
while(jump<=p-1){
temp= temp->next;
jump+=1;
}
node*n= new node(data);
n->next= temp->next;
temp->next=n;
}
}
bool searchRecursive(node*head, int key){
if(head==NULL){
return false;
}
if(head->data==key){
return true;
}
else{
return searchRecursive(head->next,key);
}
}
bool searchIteratively(node*head, int key){
if(head==NULL){
return false;
}
while(head!=NULL){
if(head==key){
return true;
}
}
void deleteAtHead(node*&head){
if(head==NULL){
return;
}
node*temp= head;
head= head->next;
delete temp;
return;
}
}
void printNode(node*head){
while(head!=NULL){
cout<<head->data<<"->";
head= head->next;
}
cout<<endl;
}
node*mid(node*head){
if(head==NULL || head->next==NULL){
return head;
}
node*slow=head;
node*fast= head->next;
while(fast!=NULL and fast-next!=NULL){
fast= fast->next->next;
slow= slow->next->next;
}
return slow;
}
bool detectCycle(node*head){
node*slow= head;
node*fast= head->next;
while(fast!=NULL and fast->next!=NULL){
fast=fast->next->next;
slow= slow->next;
if(fast==slow){
return true;
}
return false;
}
}
int main()
{
node*head=NULL;
insertAtTail(head,5);
insertAtTail(head,4);
insertAtHead(head,1);
insertAtMiddle(head,4,2);
printNode(head);
if(detectCycle()){
cout<<"Cycle is formed";
}
else{
cout<<"Cycle is not Found";
}
}