Create a link list Add some nodes to it search and delete no
Create a link list. Add some nodes to it, search and delete nodes from it
Example 1)
Define a link list node
• typedef struct node {
• int val;
• struct node * next;
• } node_t;
local variable which points to the first item of the list
• node_t * head = NULL;
• head = malloc(sizeof(node_t));
• if (head == NULL) { • return 1;
• }
• head->val = 1;
• head->next = NULL;
example 2)
Add a variable to the end of the list
• node_t * head = NULL;
• head = malloc(sizeof(node_t));
• head->val = 1;
• head->next = malloc(sizeof(node_t));
• head->next->val = 2;
• head->next->next = NULL;
Iterating over a list
• void print_list(node_t * head) {
• node_t * current = head;
• while (current != NULL) {
• printf(\"%d\ \", current->val);
• current = current->next;
• }
• }
Solution
I\'m writing add, search and delete functions for you.
void add(node_t *head, node_t nodeTobeAdded) {
while(head->next != null) {head = head->next;}
head->next = nodeTobeAdded;
head->next->next = null;
}
void search(node_t *head, int k) {
while(head->next != null) {
if(head->val == k) {printf(\"Found\"); return;}
head = head->next;
}
}
void delete(head_t *head, int k) {
while(head->next != null) {
if(head->next->val == k) {
head->next = head->next->next; // Just point head to 2nd neighbour ahead so that next node will get deleted.
}
head = head->next;
}
}


