-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLinkedList.c
122 lines (101 loc) · 2.29 KB
/
LinkedList.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
// Linked list in C, push, append
// Techie Delight https://www.techiedelight.com/linked-list-implementation-part-1/
// https://www.techiedelight.com/linked-list-implementation-part-2/
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int key;
Node* next;
} Node;
void push(Node** head, int key)
{
Node* node = (Node*)malloc(sizeof(Node));
node->key = key;
node->next = *head;
*head = node;
}
int pop(Node** head)
{
if (*head == NULL) {
return -1;
}
Node* temp = *head;
int result = temp->key;
*head = (*head)->next;
free(temp);
return result;
}
Node* constructList(int keys[], int n)
{
Node* head = NULL;
for (int i = 0; i < n; ++i) {
push(&head, keys[i]);
}
return head;
}
Node* constructListAppend(int keys[], int n)
{
Node dummy;
dummy.next = NULL;
Node* tail = &dummy;
for (int i = 0; i < n; ++i) {
push(&(tail->next), keys[i]);
tail = tail->next;
}
return dummy.next;
}
void deleteList(Node** head)
{
Node* prev = *head;
while (*head != NULL) {
*head = (*head)->next;
free(prev);
prev = *head;
}
}
Node* cloneList(Node* head)
{
Node* current = head;
Node dummy;
Node* tail = &dummy;
dummy.next = NULL;
while (current != NULL) {
push(&(tail->next), current->key);
tail = tail->next;
current = current->next;
}
return dummy.next;
}
void printList(Node* node)
{
Node* current = node;
while (current != NULL) {
printf("%d -> ", current->key);
current = current->next;
}
printf("NULL \n");
}
int main()
{
int keys[] = {1, 2, 3, 4, 5, 6};
int n = sizeof(keys) / sizeof(keys[0]);
printf("Constructing list in push mode\n");
struct Node* head = constructList(keys, n);
printList(head);
printf("Constructing list in append mode\n");
Node* head2 = constructListAppend(keys, n);
printList(head2);
printf("Cloning list 1\n");
Node* cloneList1 = cloneList(head);
printf("Cloned list:\n");
printList(cloneList1);
printf("Pop from list 1: %d\n", pop(&head));
printf("Deleting list1 and list2\n");
deleteList(&head);
deleteList(&head2);
printList(head);
printList(head2);
delete(cloneList1);
return 0;
}