-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetect_a_loop_in_LL.cpp
More file actions
81 lines (79 loc) · 1.64 KB
/
detect_a_loop_in_LL.cpp
File metadata and controls
81 lines (79 loc) · 1.64 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
// C program to detect loop in a linked list
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
/* Link list Node */
struct Node{
int data;
struct Node* next;
};
void push(struct Node** head_ref, int new_data)
{
/* allocate Node */
struct Node* new_Node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_Node->data = new_data;
/* link the old list off the new Node */
new_Node->next = (*head_ref);
/* move the head to point to the new Node */
(*head_ref) = new_Node;
}
int detectloop(struct Node *list);
/* Driver program to test above function*/
int main()
{
int t,n,c,x,i;
cin>>t;
while(t--){
/* Start with the empty list */
cin>>n;
struct Node *head = NULL;
struct Node* temp;
struct Node *s;
cin>>x;
push(&head,x);
s=head;
for(i=1;i<n;i++){
cin>>x;
push(&head,x);}
/* Create a loop for testing */
cin>>c;
if(c>0){
c=c-1;
temp=head;
while(c--)
temp=temp->next;
s->next=temp;
}
int g=detectloop(head);
if(g)
cout<<"True";
else
cout<<"False";
}
return 0;
}
/*Please note that it's Function problem i.e.
you need to write your solution in the form of Function(s) only.
Driver Code to call/invoke your function is mentioned above.*/
/*The structure of linked list is the following
struct node
{
int data;
Node* next;
};*/
int detectloop(Node *list)
{
Node* front=list;
Node* rear = list;
while(front && front->next){
rear = rear->next;
front=front->next->next;
if(rear==front)
return 1;
}
return 0;
// your code here
}