-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdoubly_linked_list.c
102 lines (79 loc) · 1.77 KB
/
doubly_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
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
struct Node *prev;
};
struct Node *head = NULL;
struct Node* createNode(int);
void insertAtHead(int);
void insertAtTail(int);
void printList();
void reversePrint();
int main() {
for (int i = 0; i < 5; i++) {
insertAtHead(i);
}
insertAtTail(100);
insertAtTail(101);
insertAtTail(102);
printList();
reversePrint();
return 0;
}
struct Node* createNode(int data) {
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> data = data;
newNode -> prev = NULL;
newNode -> next = NULL;
return newNode;
}
void insertAtHead(int data) {
struct Node *newNode = createNode(data);
// if list head is NULL, then set the `head = Node`
if (head == NULL) {
head = newNode;
return;
}
head -> prev = newNode;
newNode -> next = head;
head = newNode;
}
void printList() {
// curr refers to temporary current node
struct Node *curr = head;
printf("List: ");
while (curr != NULL) {
printf("%i ", curr -> data);
curr = curr -> next;
}
printf("\n");
}
void reversePrint() {
printf("Reverse List: ");
if (head == NULL) {
return;
}
struct Node *curr = head;
while (curr -> next != NULL) {
curr = curr -> next;
}
while (curr != NULL) {
printf("%i ", curr -> data);
curr = curr -> prev;
}
}
void insertAtTail(int data) {
struct Node *newNode = createNode(data);
if (head == NULL) {
head = newNode;
return;
}
struct Node *curr = head;
while (curr -> next != NULL) {
curr = curr -> next;
}
curr -> next = newNode;
newNode -> prev = curr;
}