Write a program that fills a stack called stack1 with the numbers 3,5,1,2,4 (in
ID: 3557311 • Letter: W
Question
Write a program that fills a stack called stack1 with the numbers 3,5,1,2,4 (in this order).
Your program should then use two other stacks, stack2 and stack3, and the functions push and pop so that in the end, stack3 contains 1,2,3,4,5
Your program should display the contents of each stack after a push. Count how many pops it takes to get the values in order on stack3.
Here is an example of what the stack would look like:
Start position
4
2
1
5
3
Stack1 Stack2 Stack3
Step1
4
2
1
5
3 4
Stack1 Stack2 Stack3
Step2
1
5 2
3 4
Stack1 Stack2 Stack3
Step3
5 2
3 4 1
Stack1 Stack2 Stack3
Step4
5 2
3 4 1
Stack1 Stack2 Stack3
Step5
3
5 2
4 1
Stack1 Stack2 Stack3
Step6
3
2
5 4 1
Stack1 Stack2 Stack3
Step7
4
3
2
5 1
Stack1 Stack2 Stack3
Step8
5
4
3
2
1
Stack1 Stack2 Stack3
Explanation / Answer
// StackImplementation.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<conio.h>
#include<iostream>
#define MAX 5
using namespace std;
int t=0;
class stack
{
int s[5];
public:
void push(int);
int pop();
void top();
bool empty();
void show();
};
void stack::push(int y) //Push Operation
{
if(t<MAX)
{
t++;
s[t]=y;
cout<<s[t]<<endl;
}
else
cout<<endl<<"stack overflows..."<<endl;
}
int stack::pop() //Pop Operation
{
int item;
if(t>=0)
{
t--;
item=s[t+1];
cout<<item<<endl;
return item;
}
else
{
cout<<endl<<"stack underflows"<<endl;
return 0;
}
}
void stack::top() //To find the top of the stack
{
if(t>=0)
cout<<endl<<"topmost element >> "<<s[t]<<endl;
else
cout<<endl<<"stack underflows..."<<endl;
}
bool stack::empty() //To check if the stack is empty
{
if(t<0)
{
cout<<endl<<"stack is empty..."<<endl;
return 1;
}
else{
cout<<endl<<"stack is not empty..."<<endl;
return 0;
}
}
int main()
{
int a,x;
int arr[5]={4,2,1,5,3};
stack s1,s2,s3;
for(int i=0;i<5;i++)
{
s1.push(arr[i]);
}
cout<<"===================";
do
{
if(s1.pop()==1)
{
s3.push(s1.pop());
}
else
{
s2.push(s1.pop());
}
}while(s1.empty());
s3.push(s1.pop());
if(s1.pop()>s2.pop())
{
s3.push(s2.pop());
}
if(s1.pop()>s2.pop())
{
s2.push(s1.pop());
s3.push(s1.pop());
s1.push(s2.pop());
s3.push(s2.pop());
s3.push(s1.pop());
}
for(int i=0;i<5;i++)
{
s3.top();
}
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.