Thursday, October 13, 2016

Write a program to create a queue from a stack. After the queue has been created,the top of the stack should be the front of the queue and the base of the stack should be the rear of the queue

#include<bits/stdc++.h>
using namespace std;

struct node
{
int data;
struct node *next;
}*node;

struct head
{
int count;
struct node *p;
}*head;

struct head1
{
int count1;
struct node *front;
struct node *rear;
}*head1;

void create_node()
{
node=(struct node*) malloc (sizeof(struct node));
node->next=NULL;
}

void create_head()
{
head=(struct head*) malloc (sizeof(struct head));
head->count=0;
head->p=NULL;
}

void create_head1()
{
head1=(struct head1*) malloc (sizeof(struct head1));
head1->count1=0;
head1->front=NULL;
head1->rear=NULL;
}

void push(int x)
{
create_node();
node->data=x;

node->next=head->p;
head->p=node;

head->count++;
}

int  pop()
{
int x;

if(head->count==1)
{
x=head->p->data;
free(head->p);
head->p=NULL;
}
else
{
struct node *temp;

temp=head->p;
x=temp->data;
head->p=temp->next;
free(temp);
}

head->count--;
return x;
}

void print()
{
struct node *temp;

temp=head->p;

while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}

cout<<"\ntotal data "<<head->count<<endl<<endl;
}

void enqueue(int data)
{
    create_node();
    node->data=data;

    if(head1->count1==0)
    {
        head1->front=node;
        head1->rear=node;
    }
    else
    {
        head1->rear->next=node;
        head1->rear=node;
    }

    head1->count1++;
}

void print1()
{
struct node *temp;

temp=head1->front;

cout<<"The queue data are : ";

while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}

cout<<"\ntotal data "<<head1->count1<<endl;
cout<<"Front of the queue : "<<head1->front->data<<endl;
cout<<"The rear of the queue : "<<head1->rear->data<<endl<<endl;
}



int main()
{
create_head();
create_head1();

push(16);
push(46);
push(54);
push(75);
push(54);
push(64);
push(43);
push(76);
cout<<"\nBefore constructing queue the stack data are : "<<endl;
print();


    int x=head->count;

    while(x--)
{
enqueue(pop());
}

print1();

cout<<"After constructing queue the stack data are : "<<endl;
print();

return 0;
}

No comments:

Post a Comment