Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct queue{
- int data; //data contains information to be linked
- struct queue *next; //next points to the next node of type queue
- }*front = NULL;//initially the queue is empty
- struct queue* create(int value){
- struct queue *newNode = (struct queue *)malloc(sizeof(struct queue));//allocate space for node
- newNode->data = value; newNode->next = NULL;
- printf("\nA new Node has been created.\n");
- return newNode;
- }
- void enqueue(struct queue *newNode){
- struct queue *help = front;
- if(!front) front = newNode;
- else{
- while(help->next) help = help->next;//Traversing to find insertiton point
- help->next = newNode;
- }
- }
- void dequeue(){//Front-most element gets deleted{
- struct queue *target = front;
- front = front->next;
- free(target);//freeing prevents memory leaks
- }
- void display(){
- struct queue *help = front;
- if(!front) printf("\nThe Queue is empty.");
- else while(help){
- printf(" %d ",help -> data);
- help = help -> next;
- }
- }
- int main(){
- int n;
- while(1){
- display();
- printf(" \n1.Enqueue 2.Dequeue 3.Exit: ");
- scanf("%d", &n);
- switch(n){
- case 1: printf("\nEnter a number to insert at the rear of the queue: ");
- scanf("%d",&n);
- enqueue(create(n));//after creating a new node, it'll be inserted
- break;
- case 2: if(front) dequeue();//if the queue is not empty, dequeue will happen
- else printf("Error: Underflow.");
- break;
- case 3: return 0;
- default:printf("\nInput Error. Try again.");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement