-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloop.cpp
74 lines (71 loc) · 1.06 KB
/
loop.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
#include<iostream>
#include<cstdlib>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}node;
void create(node ** head,int n)
{
node *temp;
if(*head == NULL) {
temp = (node *)malloc(sizeof(node));
temp->data = n;
*head = temp;
(*head)->next = NULL;
}else {
create((&(*head)->next),n);
}
}
void print(node *head)
{
while(head != NULL) {
cout << head->data << "-->";
head = head->next;
}
}
void loop(node *head)
{
int flag = 0;
node *slow = head;
node *fast = head;
while(slow && fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if(slow == fast) {
flag = 1;
break;
}
}
if(flag == 1) {
cout << "loop exists\n";
}else {
cout << "no loop exists\n";
}
}
int main()
{
int count = 0;
node *head = NULL;
while(1) {
//create(&head,n);
int n;
cin >> n;
if(n == 999) {
break;
}else {
create(&head,n);
}
}
print(head);
node *temp = head;
while(count != 4) {
temp = temp->next;
count++;
}
temp = head;
//head->next->next->next->next = head;
loop(head);
return 0;
}