-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem22.c
More file actions
96 lines (76 loc) · 1.6 KB
/
problem22.c
File metadata and controls
96 lines (76 loc) · 1.6 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
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct Node{
int data;
struct Node *next;
} Node;
Node *createNode(int data){
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
int detectAndRemoveLoop(Node *head){
Node *slow = head, *fast = head;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast) break;
}
if(!fast || !fast->next) return 1;
slow = head;
if(slow == fast){
while(fast->next != slow)
fast = fast->next;
}
else{
while(slow->next != fast->next){
slow = slow->next;
fast = fast->next;
}
}
fast->next = NULL;
return 1;
}
void createLoop(Node *head, int pos){
if(pos <= 0) return;
Node *loopNode = NULL;
Node *temp = head;
int count = 1;
while(temp->next){
if(count == pos) loopNode = temp;
temp = temp->next;
count++;
}
if(loopNode)
temp->next = loopNode;
}
int main(){
Node *head = NULL, *tail = NULL;
char buffer[100];
int value;
printf("Enter node values: ");
while(fgets(buffer, sizeof(buffer), stdin)){
if(buffer[0] == '\n') break;
if(sscanf(buffer, "%d", &value) != 1) break;
Node *newNode = createNode(value);
if(!head)
head = tail = newNode;
else{
tail->next = newNode;
tail = newNode;
}
}
if(!head){
printf("False\n");
return 0;
}
int pos;
printf("Position = ");
scanf("%d", &pos);
createLoop(head, pos);
int result = detectAndRemoveLoop(head);
printf(result ? "true\n" : "false\n");
return 0;
}