Advertisement
Shailrshah

Insertion & Deletion in a Sorted Linked List

Aug 15th, 2013
951
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.49 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct node{
  4.         int data;
  5.         struct node* next;
  6. } *head = NULL;
  7. int display(){
  8.     if(!head)   printf("Linked List is empty!");
  9.     else{
  10.         struct node* help = head;
  11.         printf("| %d |-->",help);
  12.         while (help != NULL){
  13.             printf("| %d | %d |-->", help->data, help->next);
  14.             help = help -> next;
  15.         }
  16.     }
  17. }
  18. void insert(int value){
  19.     struct node *newNode = (struct node*) malloc(sizeof(struct node*));//Create space for new node
  20.     newNode->data = value;
  21.     if(!head || value <= head->data){ //Inserting in the front
  22.         if(head) newNode->next = head;
  23.         else newNode->next = NULL;
  24.         head = newNode;
  25.     } else{
  26.         struct node *help = head, *prev = NULL;
  27.         while(help && value > help->data){
  28.             prev = help;
  29.             help = help ->next; //Traverse linked list
  30.         }
  31.         newNode->next = help; //Inserting in middle or to the back
  32.         prev->next = newNode;
  33.     }
  34. }
  35. void remove(int value){
  36.     struct node* help = head, *prev = NULL;
  37.     while(help){//Traversal until match found
  38.         if(help->data == value) break;
  39.         prev = help;
  40.         help = help->next;
  41.     }
  42.     if(!help) printf("\nValue not Found.\n");
  43.     else{
  44.         struct node *target = help;//target is the node to be deleted
  45.         if(target == head) head = head->next;//deleting from front
  46.         else prev->next = target->next;//deleting from the middle/end
  47.         free(target);
  48.     }
  49. }
  50. int main(){
  51.     int n;
  52.     while(1){
  53.         display();
  54.         printf("\n\n1. Instert 2. Delete 3. Exit: ");
  55.         scanf("%d", &n);
  56.         switch(n){
  57.             case 1:
  58.                 printf("\nEnter an element to insert: ");
  59.                 scanf("%d", &n);
  60.                 insert(n);
  61.                 break;
  62.             case 2:
  63.                 if(head){
  64.                     printf("\nEnter an Element to delete: ");
  65.                     scanf("%d", &n);
  66.                     remove(n);
  67.                 }
  68.                 break;
  69.             default:
  70.                 printf("\nTry again.\n");
  71.                 break;
  72.             case 3:
  73.                 printf("\nMore programs @ pastebin.com/u/ShailRShah");
  74.                 return 0;
  75.         }
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement