forked from rathoresrikant/HacktoberFestContribute
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cir_linked_list.c
113 lines (82 loc) · 1.6 KB
/
cir_linked_list.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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct node {
int data;
struct node* next;
} node_t;
node_t* head = NULL;
node_t* current = NULL;
bool empty() {return head == NULL;}
int length() {
int length = 0;
//if list is empty
if(head == NULL)
return 0;
current = head->next;
while(current != head) {
length++;
current = current->next;
}
return length;
}
void push(int data) {
//create a link
node_t* link = malloc(sizeof(node_t));
link->data = data;
if (empty()) {
head = link;
head->next = head;
} else {
//point it to old first node
link->next = head;
//point first to new first node
head = link;
}
}
//delete first item
node_t* pop() {
//save reference to first link
node_t* temp = head;
if(head->next == head) {
head = NULL;
return temp;
}
//mark next to first link as first
head = head->next;
//return the deleted link
return temp;
}
//display the list
void print() {
node_t* current= head;
printf(" [ ");
//start from the beginning
if(head != NULL) {
while(current->next != current) {
printf("%d ", current->data);
current = current->next;
}
}
printf(" ]");
}
int main(void) {
push(10);
push(20);
push(30);
push(1);
push(40);
push(56);
printf("Original List: ");
//print list
print();
while(!empty()) {
node_t* temp = pop();
printf("\nDeleted value:");
printf("%d ",temp->data);
}
printf("\nList after deleting all items: ");
print();
return 0;
}