Advertisement
Shailrshah

Sorted Doubly Linked List

Aug 29th, 2013
321
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.24 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct node{
  4.     int data;
  5.     struct node *prev,*next;
  6. } *head = NULL;
  7. struct node *create(int value){
  8.     struct node *newNode = (struct node*) malloc(sizeof(struct node));
  9.     newNode->data = value; newNode->prev = newNode->next = NULL;
  10.     return newNode;
  11. }
  12. void insert(struct node *newNode){
  13.     struct node *help = head;
  14.     if(!head || newNode->data < head->data){ //Front insertion
  15.         if(head){
  16.             newNode->next = head;
  17.             head->prev = newNode;
  18.         }
  19.         head = newNode;
  20.     }
  21.     else{
  22.         while(help->next && newNode->data >= help->data) help = help->next;
  23.         if(!help->next && newNode->data >= help->data){ //Back insertion
  24.             help->next = newNode;
  25.             newNode->prev = help;
  26.         }
  27.         if(newNode->data < help->data){ //Middle insertion
  28.             newNode->next = help;
  29.             newNode->prev = help->prev;
  30.             help->prev->next = newNode;
  31.             help->prev = newNode;
  32.         }
  33.     }
  34. }
  35. void delet(int value){
  36.     struct node *help = head, *target = NULL;
  37.     while(help && help->data != value) help = help->next;
  38.     if(!help) printf("\nData not found.");
  39.     else{
  40.         target = help;
  41.         if(target == head) head = head->next;
  42.         else{
  43.             if(target->prev) target->prev->next = target->next;
  44.             if(target->next) target->next->prev = target->prev;
  45.         }
  46.         free(target);
  47.     }
  48. }
  49. void display(){
  50.     struct node *help = head;
  51.     printf("\nThe list is: ");
  52.     if(!head) printf("Empty.");
  53.     while(help){
  54.         printf("\t%d\t", help->data);
  55.         help = help->next;
  56.     }
  57. }
  58. int main(){
  59.     int choice, n;
  60.     while(1){
  61.         display();
  62.         printf("\n\n1.Insert 2.Delete 3.Exit: ");
  63.         scanf("%d", &choice);
  64.         switch(choice){
  65.             case 1: printf("Enter the value to enter: ");
  66.                     scanf("%d", &n);
  67.                     insert(create(n));
  68.                     break;
  69.             case 2: if(head){
  70.                         printf("Enter the value to delete: ");
  71.                         scanf("%d", &n);
  72.                         delet(n);
  73.                     }break;
  74.             case 3: return 0;
  75.         }
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement