Tuesday, 3 November 2015

Queue implemented as linked list in CPP -Data Structures

#include<iostream>
using namespace std;
struct node
{
int data;
struct node *link;
};
struct node *front=NULL,*rear=NULL;

void enqueue(int val)
{
if(front==NULL && rear==NULL)
{
node *newnode=new node;
newnode->data=val;
newnode->link=NULL;
rear=front=newnode;
}
else
{
node *newnode=new node;
newnode->data=val;
newnode->link=NULL;
rear->link=newnode;
rear=newnode;
}
}
void dequeue()
{
if(front==NULL)
cout<<"\nQUEUE IS EMPTY!";
else if (front==rear)//only one node is left
{
front=NULL;
rear=NULL;
}
else
{
front=front->link;
}
}
void display()
{
if(front==NULL)
cout<<"\nQUEUE IS EMPTY!";
else
{
node *temp=front;
while(temp!=NULL)
{
cout<<temp->data<<"\t";
temp=temp->link;
}
}
}
int main()
{
int choice,val;
while(1)
{
cout<<"\nQUEUE LINKED LIST \n1.Enqueue 2.Dequeue 3.Display 4.Exit \nEnter your choice:";
cin>>choice;
switch(choice)
{
case 1:
   cout<<"\nEnter value:";cin>>val;
   enqueue(val);
   break;
case 2:
   dequeue();
   break;
case 3:
   display();
   break;
case 4:
   return 0;
   break;
default:
cout<<"\nCheck ur input\n";
}
}
return 0;
}


OUTPUT:


QUEUE LINKED LIST
1.Enqueue 2.Dequeue 3.Display 4.Exit
Enter your choice:1
Enter value:7

QUEUE LINKED LIST
1.Enqueue 2.Dequeue 3.Display 4.Exit
Enter your choice:1
Enter value:5

QUEUE LINKED LIST
1.Enqueue 2.Dequeue 3.Display 4.Exit
Enter your choice:1
Enter value:6

QUEUE LINKED LIST
1.Enqueue 2.Dequeue 3.Display 4.Exit
Enter your choice:2

QUEUE LINKED LIST
1.Enqueue 2.Dequeue 3.Display 4.Exit
Enter your choice:3

5       6

No comments:

Post a Comment