-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list_song.c
More file actions
executable file
·114 lines (93 loc) · 2.14 KB
/
linked_list_song.c
File metadata and controls
executable file
·114 lines (93 loc) · 2.14 KB
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
#include <stdio.h>
#include <stdlib.h>
struct node
{
char str[];
struct node *next;
} *
void insertAtBeginning(struct Node **ref, char data[])
{
// Allocate memory to a node
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
// insert the item
new_node->item = data;
new_node->next = (*ref);
// Move head to new node
(*ref) = new_node;
}
// Insert a node after a node
void insertAfter(struct Node *node, char data[])
{
if (node == NULL)
{
printf("the given previous node cannot be NULL");
return;
}
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
new_node->item = data;
new_node->next = node->next;
node->next = new_node;
}
void insertAtEnd(struct Node **ref, char data[
])
{
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
struct Node *last = *ref;
new_node->item = data;
new_node->next = NULL;
if (*ref == NULL)
{
*ref = new_node;
return;
}
while (last->next != NULL)
last = last->next;
last->next = new_node;
return;
}
void deleteNode(struct Node **ref, char key[])
{
struct Node *temp = *ref, *prev;
if (temp != NULL && temp->item == key)
{
*ref = temp->next;
free(temp);
return;
}
// Find the key to be deleted
while (temp != NULL && temp->item != key)
{
prev = temp;
temp = temp->next;
}
// If the key is not present
if (temp == NULL)
return;
// Remove the node
prev->next = temp->next;
free(temp);
}
// Print the linked list
void printList(struct Node *node)
{
while (node != NULL)
{
printf(" %s ", node->item);
node = node->next;
}
}
int main()
{
char song[];
struct Node *head = NULL;
insertAtEnd(&head, "red");
insertAtBeginning(&head, "dangerously");
insertAtBeginning(&head, "attention");
insertAtEnd(&head, "blue");
insertAfter(head->next, 5);
printf("Linked list: ");
printList(head);
printf("\nAfter deleting an element: ");
deleteNode(&head, "random");
printList(head);
}