Advertisement
Shailrshah

Doubly-Ended Queues

Sep 27th, 2013
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.31 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct node{
  4.         int data;
  5.         struct node *next, *prev;
  6. } *head = NULL, *tail = NULL;
  7. void display(struct node *help){
  8.     if(!help) printf("\nEmpty Queue.");
  9.     else while(help){
  10.             printf(" %d ", help->data);
  11.             help = help->next;
  12.         }
  13. }
  14. void frontInsert(struct node *newNode){
  15.         newNode->prev = NULL;
  16.         newNode->next = head;
  17.         if(!head) tail = newNode;
  18.         else head->prev = newNode;
  19.         head = newNode;
  20. }
  21. void backInsert(struct node *newNode){
  22.         newNode->next = NULL;
  23.         newNode->prev = tail;
  24.         if(!tail) head = newNode;
  25.         else tail->next = newNode;
  26.         tail = newNode;
  27. }
  28. void frontDelete(){
  29.         if(!head->next) head = tail = NULL;
  30.         else{
  31.             struct node *target = head;
  32.             head = head->next;
  33.             head->prev = NULL;
  34.             free(target);
  35.         }
  36. }
  37. void backDelete(){
  38.     if(!tail->prev) tail = head = NULL;
  39.     else{
  40.         struct node *target = tail;
  41.         tail = tail->prev;
  42.         tail->next = NULL;
  43.         free(target);
  44.     }
  45. }
  46. int main(){
  47.     int choice, value;
  48.     while(1){
  49.         display(head);
  50.         printf("\n1. Insert 2. Delete 3. Exit: ");
  51.         scanf("%d", &choice);
  52.         switch(choice){
  53.             case 1:{
  54.                 printf("\nEnter the value to be inserted: ");
  55.                 scanf("%d", &value);
  56.                 printf("\nInsert at 1. Front 2. Back: ");
  57.                 scanf("%d",&choice);
  58.                 struct node *newNode = (struct node*) malloc(sizeof(struct node));
  59.                 newNode->data = value;
  60.                 if(choice == 1) frontInsert(newNode);
  61.                 else if(choice == 2) backInsert(newNode);
  62.                 else goto down;
  63.                 break;
  64.             }
  65.             case 2: if(!head) printf("\nCan't Delete.");
  66.                     else{
  67.                         printf("\nDelete from 1. Front 2. Back: ");
  68.                         scanf("%d", &choice);
  69.                         if(choice == 1) frontDelete();
  70.                         else if(choice == 2) backDelete();
  71.                         else goto down;
  72.                     } break;
  73.             case 3: return 0;
  74.             default: down: printf("\nInvalid input.");
  75.         }
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement