Dynamic Implementation of Queue in C++ using linked list

Dynamic Implementation of Queue in C++ using linked list

#include <iostream.h>
#include <conio.h>

class queue
{
    struct node
    {
        int info;
        node *next;
    }*rear,*front;
    public:
        queue(){rear=front=NULL;}
        void push();
        void pop();
        void display();
};

void queue::push()
{
    int data;
    node *newnode;
    newnode=new node;
    cout<<"Enter the data"<<endl;
    cin>>data;
    newnode->info=data;
    newnode->next=NULL;
    if(rear==NULL)
    {
        front=newnode;
        rear=newnode;
    }
    else
    {
        rear->next=newnode;
        rear=newnode;
    }

}

void queue::pop()
{
    node *temp=front;
    if(front==NULL && rear==NULL) cout<<"Queue is empty"<<endl;
    else
    {
        front=temp->next;
        cout<<"The data is:"<<temp->info;
    }
    delete temp;
    if(front==NULL) rear=NULL;
}

void queue::display()
{
    int a=0;
    node *temp=front;
    cout<<"The items in the queueare"<<endl;
    while(temp!=NULL)
    {
        a++;
        cout<<a<<"."<<temp->info<<endl;
        temp=temp->next;
    }
    if(a==0)
    {
        clrscr();
        cout<<"Queue is empty";
    }
}

void main()
{
    int ch;
    queue a;
    do
    {
        clrscr();
        cout<<"Menu"<<endl;
        cout<<"1.Push operation"<<endl;
        cout<<"2.Pop operation"<<endl;
        cout<<"3.Display"<<endl;
        cout<<"4.Exit"<<endl;
        cout<<"Enter ur choice:";
        cin>>ch;
        switch(ch)
        {
            case 1:
                a.push();
                break;
            case 2:
                a.pop();
                break;
            case 3:
                a.display();
                break;
            case 4:
                break;
            default:
                cout<<"Out of menu"<<endl;
                break;
        }
        getch();
    }while(ch!=4);

}

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...