-
Notifications
You must be signed in to change notification settings - Fork 0
/
circularLinkList.c
101 lines (84 loc) · 1.92 KB
/
circularLinkList.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
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
int key;
struct node *next;
};
struct node *head = NULL;
struct node *current = NULL;
bool isEmpty() { 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;
}
// Insert link at first location
void insertFirst(int key, int data) {
// Create a link
struct node *link = (struct node *)malloc(sizeof(struct node));
link->key = key;
link->data = data;
if (isEmpty()) {
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
struct node *deleteFirst() {
// Save reference to first link
struct node *tempLink = head;
if (head->next == head) {
head = NULL;
return tempLink;
}
// Mark next to first link as first
head = head->next;
// Return the deleted link
return tempLink;
}
// Display the list
void printList() {
struct node *ptr = head;
printf("\n[ ");
// Start from the beginning
if (head != NULL) {
while (ptr->next != ptr) {
printf("(%d,%d) ", ptr->key, ptr->data);
ptr = ptr->next;
}
}
printf(" ]");
}
int main() {
insertFirst(1, 10);
insertFirst(2, 20);
insertFirst(3, 30);
insertFirst(4, 1);
insertFirst(5, 40);
insertFirst(6, 56);
printf("Original List: ");
// Print list
printList();
while (!isEmpty()) {
struct node *temp = deleteFirst();
printf("\nDeleted value:");
printf("(%d,%d) ", temp->key, temp->data);
}
printf("\nList after deleting all items: ");
printList();
}