-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsgLLfindingLoop.cpp
More file actions
116 lines (103 loc) · 1.92 KB
/
sgLLfindingLoop.cpp
File metadata and controls
116 lines (103 loc) · 1.92 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
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
#include<iostream>
#include<string>
using namespace std;
#define null 0
struct node
{
string data;
node *next;
};
node *first,*temp,*ttemp,*i,*j;
void init()
{first=temp=ttemp=null;}
void addnode()
{
ttemp=new node;
cin>>ttemp->data;
ttemp->next=null;
if(first==null)
first=ttemp;
else
temp->next=ttemp;
temp=ttemp;
}
void disp()
{
temp=first;
while(temp!=null)
{
cout<<temp->data<<"\n";
temp=temp->next;
}
}
void createLoop(node* head, int pos) {
if (pos == 0) return;
node* loopNode = head;
for (int i = 1; i < pos; i++)
loopNode = loopNode->next;
node* temp = head;
while (temp->next)
temp = temp->next;
temp->next = loopNode;
}
bool hasLoop(node*head)
{
node*slow=head;
node*fast=head;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
return true;
}
return false;
}
void removeLoop(node*head)
{
node*slow=head;
node*fast=head;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
break;
}
if(slow!=fast)
return;
slow=head;
while(slow!=fast)
{
slow=slow->next;
fast=fast->next;
}
while (fast->next != slow)
fast = fast->next;
fast->next = NULL;
}
int main()
{
init();
int n,loopPos;
cout<<"enter number of names u want to enter: ";
cin>>n;
for(int i=1;i<=n;i++)
{
addnode();
}
cout<<"\noriginal sequence\n";
disp();
cout << "Enter position to create loop (0 for no loop): ";
cin >> loopPos;
createLoop(first, loopPos);
cout<<"\n";
if(hasLoop(first))
{
cout<<"The given LL has a inner loop\n";
removeLoop(first);
cout<<"list after removing loop\n";
disp();
}
else cout<<"The given LL is perfect";
}