-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedListImpl.c
132 lines (110 loc) · 2.5 KB
/
linkedListImpl.c
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
#include <stdio.h>
#include <malloc.h>
typedef struct Node {
int data;
struct Node* next;
} node;
node* newNode(int d){
node* x = (node*)malloc(sizeof(node));
x->data = d;
x->next = NULL;
return x;
}
void append(node** head, int d){
node* nodeToAdd = newNode(d);
if (isEmpty(*head)) {
*head = nodeToAdd;
}
else {
node* temp = *head;
while(temp->next!=NULL) temp=temp->next;
temp->next = nodeToAdd;
}
}
int isEmpty(node* head){
if(head==NULL) return 1;
else return 0;
}
node* deleteLastNode(node** head){
if(isEmpty(*head)){
printf("Cannot delete anything, list is already empty\n");
return NULL;
}
else{
node* temp = *head;
while(temp->next->next!=NULL) temp=temp->next;
node* removed = temp->next;
temp->next = NULL;
return removed;
}
}
void printList(node* head){
if(head==NULL){
printf("the list is empty\n");
return;
}
node* temp = head;
while(temp!=NULL){
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
/*
n: the number of node where the loop starts from.
n=1 means the loop starts at the first node.
*/
void makeCircularList(node** head, int n){
if(*head==NULL) return;
if( (*head)->next==NULL ) return;
node* temp = *head;
node* beginning_of_loop = NULL;
int count=1;
while(temp->next!=NULL){
if(count==n){
beginning_of_loop = temp;
printf("beginning of loop is at node: %d\n", beginning_of_loop->data);
}
temp=temp->next;
count++;
}
if(beginning_of_loop==NULL || beginning_of_loop->next==NULL) return;
temp->next = beginning_of_loop;
printf("%d\n", temp->next->data);
}
int findStartOfCircularList(node* head){
node* t_fast = head;
node* t_slow = head;
while(t_slow!=NULL){
t_fast = t_fast->next->next;
t_slow = t_slow->next;
printf("t_fast: %d ",t_fast->data);
printf("t_slow: %d\n",t_slow->data);
if(t_slow==t_fast) break;
}
node* temp = head;
while(t_fast!=temp){
printf("t_fast: %d ",t_fast->data);
printf("temp: %d\n",temp->data);
temp = temp->next;
t_fast = t_fast->next;
}
return temp->data;
}
int main(){
node *p = (node*) malloc(sizeof(node));
p = NULL;
append(&p, 1);
append(&p, 2);
append(&p, 3);
append(&p, 4);
append(&p, 5);
append(&p, 6);
append(&p, 7);
append(&p, 8);
// append(&p, 9);
printList(p);
makeCircularList(&p, 3);
printf("the loop starting node's data node is: %d\n", findStartOfCircularList(p) );
return 1;
}