Advertisement
Shailrshah

Queues using Linked List

Sep 1st, 2013
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.75 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct queue{
  4.     int data; //data contains information to be linked
  5.     struct queue *next; //next points to the next node of type queue
  6. }*front = NULL;//initially the queue is empty
  7. struct queue* create(int value){
  8.     struct queue *newNode = (struct queue *)malloc(sizeof(struct queue));//allocate space for node
  9.     newNode->data = value; newNode->next = NULL;
  10.     printf("\nA new Node has been created.\n");
  11.     return newNode;
  12. }
  13. void enqueue(struct queue *newNode){
  14.     struct queue *help = front;
  15.     if(!front) front = newNode;
  16.     else{
  17.       while(help->next) help = help->next;//Traversing to find insertiton point
  18.       help->next = newNode;
  19.     }
  20. }
  21. void dequeue(){//Front-most element gets deleted{
  22.     struct queue *target = front;
  23.     front = front->next;
  24.     free(target);//freeing prevents memory leaks
  25. }
  26. void display(){
  27.     struct queue *help = front;
  28.     if(!front) printf("\nThe Queue is empty.");
  29.     else while(help){
  30.         printf("  %d  ",help -> data);
  31.         help = help -> next;
  32.     }
  33. }
  34. int main(){
  35.     int n;
  36.     while(1){
  37.         display();
  38.         printf(" \n1.Enqueue 2.Dequeue 3.Exit: ");
  39.         scanf("%d", &n);
  40.         switch(n){
  41.             case 1: printf("\nEnter a number to insert at the rear of the queue: ");
  42.                     scanf("%d",&n);
  43.                     enqueue(create(n));//after creating a new node, it'll be inserted
  44.                     break;  
  45.             case 2: if(front) dequeue();//if the queue is not empty, dequeue will happen
  46.                     else printf("Error: Underflow.");
  47.                     break;            
  48.             case 3: return 0;              
  49.             default:printf("\nInput Error. Try again.");              
  50.     }
  51.   }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement