Queue Implementation using Linked List

 #include<stdio.h>

#include<conio.h>

#include<stdlib.h>

void enqueue(int);

void dequeue();

void display();

void peek();

struct node{

int data;

struct node *next;

};

struct node *newnode, *front=0,*rear=0, *temp;

void main(){

enqueue(3);

enqueue(5);

enqueue(7);

enqueue(9);

display();

peek();

dequeue();

display();

peek();

getch();

}

void enqueue(int x){

newnode=(struct node*)malloc(sizeof(struct node));

newnode->data=x;

newnode->next=0;

if(front==0 && rear==0)

front=rear=newnode;

else{

rear->next=newnode;

rear=newnode;

}

}

void display(){

temp=front;

if(front==0 && rear==0)

printf("\nQueue is empty.");

else{

printf("\nCurrent elements of queue: ");

while(temp!=0){

printf("%d\t",temp->data);

temp=temp->next;

}

}

}

void peek(){

if(front==0 && rear==0)

printf("\nQueue is empty.");

else

printf("\nFront element is %d",front->data);

}

void dequeue(){

temp=front;

if(front==0 && rear==0)

printf("\nQueue is empty.");

else{

printf("\nDequeued element: %d",front->data);

front=front->next;

free(temp);

}

}


No comments:

Post a Comment