#include #include struct node { int data; struct node *next; }; void print_linked_list(struct node *head) { struct node *temp = head; if (temp == NULL) { printf("[X]\n"); return; } while (temp!=NULL) { printf("%d -> ", temp->data); temp = temp->next; } printf("[X]\n"); } void search_linked_list(struct node* head, int data) { struct node* temp; int pos = 0; temp = head; while(temp!=NULL) { if(temp->data==data) printf("Found %d at position: %d\n", data, pos); temp = temp->next; pos ++; } } struct node* insert_linked_list(struct node* head, int i, int index) { // test head == NULL // if index > length of linked list, return -1 struct node* temp, *cur; temp = (struct node *) malloc(sizeof(struct node)); temp->data = i; if(index == 0) { temp->next = head; head = temp; } else { cur = head; while (index--) { cur = cur->next; } temp->next = cur->next; cur->next = temp; } return head; } int main(void) { int num; struct node *head = NULL; struct node *temp; int value; /* * Task1: Create linked list from user input */ for(num=0; num<5; num++){ printf("enter node data: "); scanf("%d", &value); temp = (struct node *) malloc(sizeof(struct node)); temp->data = value; temp->next = head; head = temp; } /* * Task2: Print linked list */ print_linked_list(head); /* * Task4: Search element */ printf("Search: \n"); search_linked_list(head, 2); /* * Task5: Insert element */ printf("Insert: \n"); head = insert_linked_list(head, 10, 2); print_linked_list(head); /* * Task3: Free linked list space */ temp = head; while (head->next!=NULL) { temp = head; head = head->next; free(temp); print_linked_list(head); } free(head); // free will not change value of head head = NULL; // try remove this line print_linked_list(head); return 0; }