Labels

algorithms (22) Design Patterns (20) java (19) linux (14) Snippet (13) service mix (6) soa (4)

Queue

#include <iostream.h>


class element
{
public:
int value;
element* next;
};//class element

class Queue
{
public:
int size;
element* head;
element* tail;

Queue()
{
size=0;
head=NULL;
tail=NULL;
}//default constructor

void Enqueue(int);
void Dequeue();
int isEmpty();
int getQueueSize();
void printQueueSize();
void printQueueElements();
void printQueueMenu();
};

void Queue::Enqueue(int ele)
{
if(head==NULL) // first element
{
head=new element;
tail=head; //head==tail if one element
head->value=ele;
head->next=NULL;
}
else
{
tail->next=new element;
tail->next->value=ele;
tail->next->next=NULL;
cout<<tail->next->value<<endl;
tail=tail->next;
}
size++;

//printQueueElements();
}

void Queue::Dequeue()
{
if(getQueueSize()==0)
return;
else if(head==tail)
{
head=NULL;
}
else
{
element *curr,*prev; //remove the first element inserted and
curr=head; //point the head to next element
head=curr->next;
curr=NULL;
}
size--;
}

int Queue::isEmpty()
{
if(getQueueSize()==0)
return 1;

return 0;
}

int Queue::getQueueSize()
{
return size;
}//returns size of the Queue

void Queue::printQueueSize()
{
cout<<"\nThe Size of the Queue:"<<size<<"\n";
}//print the Queue size

void Queue::printQueueElements()
{
element* curr2;
curr2= head;
cout<<"\n-----\n";
cout<<"Queue\n";
cout<<"-----\n";
cout<<"size:"<<getQueueSize()<<endl;
while(curr2!=NULL)
{
cout<<" |"<<curr2->value<<"|";
curr2=curr2->next;
}
cout<<endl;
}// print the Queue

void Queue::printQueueMenu()
{
cout<<"Welcome to Queue \n";
cout<<"1.Enqueue an element\n";
cout<<"2.Dequeue an element\n";
cout<<"3.Display Queue\n";
cout<<"4.Size Of Queue\n";
cout<<"5.Exit\n";
}

void main()
{
Queue qt;
qt.printQueueMenu();
char Option=0;
int val;
while(1)
{
qt.printQueueMenu();
cin>>Option;
switch(Option)
{
case '1':
cout<<"Enter a Number \n";
cin>>val;
qt.Enqueue(val);
break;
case '2':
qt.Dequeue();
break;
case '3':
qt.printQueueElements();
break;
case '4':
qt.printQueueSize();
break;
case '5':
exit(0);
break;
}
}
}

1 comment:

  1. can any one provide me a code for insert first and insert after in doubly linked list

    ReplyDelete

Search 24 Bytes

Loading...