Thursday, October 13, 2016

write a program to create a stack from a queue. at the end of the program the queue should be unchanged.

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


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

struct head
{
int count=0;
struct node *front;
struct node *rear;
}*head;

struct head1
{
int count1;
struct node *next1;
}*head1;

struct head2
{
int count2;
struct node *next2;
}*head2;

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->front=NULL;
head->rear=NULL;
}

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

void create_head2()
{
head2=(struct head2*) malloc (sizeof(struct head2));
head2->count2=0;
head2->next2=NULL;
}

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

    if(head->count==0)
    {
        head->front=node;
        head->rear=node;
    }
    else
    {
        head->rear->next=node;
        head->rear=node;
    }

    head->count++;
}

int dequeue()
{
int x;

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

x=temp->data;

head->front=temp->next;
free(temp);
}

head->count--;

return x;
}

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

node->next=head1->next1;
head1->next1=node;

head1->count1++;
}

int  pop()
{
int x;

if(head1->count1==1)
{
x=head1->next1->data;
free(head1->next1);
head1->next1=NULL;
}
else
{
struct node *temp;

temp=head1->next1;
x=temp->data;
head1->next1=temp->next;
free(temp);
}

head1->count1--;
return x;
}

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

node->next=head2->next2;
head2->next2=node;

head2->count2++;
}

void print()
{
struct node *temp;

temp=head->front;

cout<<"The queue data are : ";

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

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

void print1()
{
struct node *temp;

temp=head1->next1;

cout<<"The stack 1 data are : ";

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

cout<<"\ntotal data "<<head1->count1<<endl<<endl;
}

void print2()
{
struct node *temp;

temp=head2->next2;

cout<<"The stack2 data are : ";

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

cout<<"\ntotal data "<<head2->count2<<endl<<endl;
}

void process()
{
int x=head1->count1;

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


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

enqueue(35);
enqueue(43);
enqueue(856);
enqueue(65);
enqueue(2);
enqueue(32);
enqueue(23);
print();

int x=head->count;

while(x--)
{
int y=dequeue();
push1(y);
enqueue(y);
}

print1();
process();
print2();
print();

}

No comments:

Post a Comment