Recursively reverse a stack - c++

I need to reverse a stack using recursion in C++. I can only use pop, push, and reverseStack, no additional functions such as insertAtBottom which I've found while search stackoverflow and the web.
I've tried:
void Stack::reverseStack(){
if (isEmpty())
return;
else{
int x;
pop(x);
reverseStack();
push(x);
}
}
but this creates a stack exactly the same as the original.

You will need to implement a function to insert an item at the bottom an example is
void Stack::insertAtBottom(int item) {
if(isEmpty())
push(item);
else {
int x;
pop(x);
insertAtBottom(item);
push(x);
}
}
At which point you can implement your reverse as follows
void Stack::reverseStack(){
if (isEmpty())
return;
else{
int x;
pop(x);
reverseStack();
insertAtBottom(x);
}
}
EDIT:
If they need to be in one function, the following is a combination of the two
void Stack::reverseStack(bool reverse=true,int item=0){
if(reverse) {
if (isEmpty())
return;
else{
int x;
pop(x);
reverseStack();
reverseStack(false,x);
}
} else {
if(isEmpty())
push(item);
else {
int x;
pop(x);
reverseStack(false,item);
push(x);
}
}
}
Cheers!

#include <iostream>
#include <stack>
using namespace std;
stack<int> S, R; // S is original stack, R is reversed stack
void reverseStack() {
if(!S.empty()) {
R.push(S.top());
S.pop();
reverseStack();
}
return;
}
int main() {
S.push(1);
S.push(2);
S.push(3);
S.push(4);
S.push(5);
reverseStack();
// Check if R is reversed
while(!R.empty()) {
cout << R.top() << " ";
R.pop();
}
return 0;
}
Hope this helps!

here is a solution to this problem in C language:
#include <stdio.h>
// functions that can be used push(), pop(), and isEmpty()
// the idea is to hold all the values in Function Call Stack until the stack becomes empty.
//When the stack becomes empty, we insert all the held items one by one at the bottom of the stack
// stack-> 1 2 3 4 becomes 4 3 2 1 when we print
#define size 4
int stk[size];
int top = -1;
void insertAtLast(int element);
int isStackFull()
{
if(top == size - 1)
return 1;
return 0;
}
void push(int val)
{
if(isStackFull()==1)
return;
else
//Task 2: Complete the logic
stk[++top] = val;
}
int isStackEmpty()
{
//Task 1: Write logic for isStackEmpty()
if (top==-1)
return 1;
return 0;
}
int pop()
{
if(isStackEmpty()==1)
return -1;
else
//Task 2: Complete the logic
return stk[top--];
}
void reverse(){
if(isStackEmpty()==1){
return;
}
int temp=pop();
reverse();
insertAtLast(temp);
}
void insertAtLast(int element){
if(isStackEmpty()==1){
push(element); //imp
return;
}
int topElements=pop(); //imp
insertAtLast(element); //imp
push(topElements);
}
int main() {
push(4);
push(3);
push(2);
push(1);
for(int i=0;i<size;i++){
printf("%d ", stk[i]);
}
printf("\n");
reverse();
for(int i=0;i<size;i++){
printf("%d ", stk[i]);
}
return 0;
}

Related

How to initialize the dynamic array of struct in the constructor?

This is a Stack class based on a dynamic array of struct for Depth First Search (DFS). The program is not able to run whenever it encounters the function, push(), which shows that the array is not successfully initialized in the constructor.
I have tried to look for the error and even changing the dynamic array of struct into parallel arrays but it still does not work. I apologize if the problem seems to be too simple to be solved as I do not have a strong foundation in C++.
#include <iostream>
#include <iomanip>
#ifndef HEADER_H
#define HEADER_H
using namespace std;
struct Value
{
int row; // row number of position
int col; // column number of position
//operator int() const { return row; }
};
class ArrayStack
{
public:
int top;
Value* array;
ArrayStack();
bool isEmpty();
bool isFull();
void push(int r, int c);
void pop();
int poprowvalue(int value);
int popcolvalue(int value);
int peekrow(int pos);
int peekcol(int pos);
int count();
void change(int pos, int value1, int value2);
void display();
void resize();
private:
int size;
};
ArrayStack::ArrayStack()
{
//Initialize all variablies
top = -1;
size = 10;
Value * array = new Value[size];
for (int i = 0; i < size; i++)
{
array[i].row = 0;
array[i].col = 0;
}
}
bool ArrayStack::isEmpty()
{
if (top == -1)
return true;
else
return false;
}
bool ArrayStack::isFull()
{
if (top == size - 1)
return true;
else
return false;
}
void ArrayStack::resize()
{
if (isFull())
size *= 2;
else if (top == size / 4)
size /= 2;
}
void ArrayStack::push(int r, int c)
{
if (isEmpty() == false)
resize();
array[top + 1].row = r;
array[top + 1].col = c;
top++;
}
void ArrayStack::pop()
{
int value;
if (isEmpty())
{
cout << "Stack underflow" << endl;
}
else
{
poprowvalue(array[top].row);
popcolvalue(array[top].col);
array[top].row = 0;
array[top].col = 0;
top--;
}
}
int ArrayStack::poprowvalue(int v)
{
return v;
}
int ArrayStack::popcolvalue(int v)
{
return v;
}
int ArrayStack::peekrow(int pos)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
return array[pos].row;
}
int ArrayStack::peekcol(int pos)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
return array[pos].col;
}
int ArrayStack::count()
{
return (top + 1);
}
void ArrayStack::change(int pos, int value1, int value2)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
{
array[pos].row = value1;
array[pos].col = value2;
}
}
void ArrayStack::display()
{
for (int i = size - 1; i > -1; i--)
{
cout << array[i].row << " " << array[i].col << endl;
}
}
#endif
I expect it to run well but an exception is always thrown on line 80, which is as follows:
Exception thrown at 0x00007FF6A160487C in Assignment1.exe: 0xC0000005: Access violation writing location 0x0000000000000000.
The problem is this line right here:
Value * array = new Value[size];
This declares a new array variable. You are allocating that array instead, and not your member variable array.
The answer is simple, just change it to this instead:
array = new Value[size];

Class MinStack not giving output

Dynamically Initialization of MinStack is not able to do. Why?
#include<bits/stdc++.h>
#include<iostream>
#include<stdlib.h>
using namespace std;
class Stack
{
int top;
int length;
int *arr;
public:
//Maximum size of Stack
Stack(int len)
{
top = -1;
length=len;
arr=new int[length];
} //constructor
void push(int data);
int pop();
bool isEmpty();
bool isStackFull();
int Size();
void Display();
int getPeek();
};
void Stack::push(int data)
{
if (isStackFull())
{
cout << "Stack Overflow"<<endl;
}
else
{
arr[++top] = data;
}
}
int Stack::pop()
{
if (isEmpty())
{
cout << "Stack Underflow"<<endl;
return 0;
}
else
{
int data = arr[top--];
return data;
}
}
bool Stack::isEmpty()
{
return (top < 0);
}
bool Stack::isStackFull()
{
return (top == length-1);
}
int Stack::Size()
{
return (top +1);
}
int Stack::getPeek()
{
return arr[top];
}
void Stack::Display()
{
for(int i=top;i!=-1;i--)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
class SpecialStack: public Stack
{
public:
Stack min1;
SpecialStack(int len):Stack(len)
{
min1= new Stack(len);
}
int pop();
void push(int x);
int getMin();
};
void SpecialStack::push(int x)
{
if(isEmpty()==true)
{
Stack::push(x);
min1.push(x);
}
else
{
Stack::push(x);
int y = min1.pop();
min1.push(y);
if( x < y )
min1.push(x);
else
min1.push(y);
}
}
/* SpecialStack's member method to remove an element from it. This method
removes top element from min stack also. */
int SpecialStack::pop()
{
int x = Stack::pop();
min1.pop();
return x;
}
int SpecialStack::getMin()
{
int x = min1.pop();
min1.push(x);
return x;
}
int main()
{
SpecialStack s(3); //size of stack should be 3
s.push(10);
s.push(20);
s.push(30);
cout<<s.getMin()<<endl;
s.push(5);
cout<<s.getMin();
return 0;
}
Dynamically Initialization of MinStack is not able to do. Why, How to rectify this problem.Please explain.
In the SpecialStack constructor you initialize the base Stack properly, but not the min1 member. They should be handled the same way:
SpecialStack(int len):Stack(len),min1(len)
{ }
When you don't have min1 in the constructors initializer list, the compiler tries do call its default constructor, but the Stack class doesn't have one.

C++ implementation of stack using array

I have studied the algorithm from Introduction to Algorithm and then
I have written this code. But in my output another value is showing for index 0. and when I use pop function it display 1 instead of 3
#include <iostream>
int top;
void initialise_top(){
top = -1;
}
bool stack_empty(int a[]){
if(top == -1)
return true;
else
return false;
}
void push(int a[], int x, int s){
if(top < s - 1){
top = top + 1;
a[top] = x;
}
else
std::cout << "overflow" << "\n";
}
int pop(int a[]){
if (stack_empty(a) == true)
std::cout << "Underflow" << "\n";
else{
--top;
return a[top+1];
}
}
void display(int a[]){
for(int i = 0;i <= top; i++){
std::cout << a[i] << " ";
}
}
int main()
{
int arr[7];
push(arr,15,7);
push(arr,6,7);
push(arr,2,7);
push(arr,9,7);
push(arr,17,7);
push(arr,3,7);
display(arr);
std::cout << "\n";
int out = pop(arr);
std::cout << pop << "\n";
return 0;
}
Here is the snapshot of the output
enter image description here
In your implementatiton you have "initialise_top()" function.
void initialise_top(){
top=-1;
}
But you don't call it in main function. If you don't call it you can't initialize "top" variable and "top" variable will hold garbage value.
You can read details in here :
Default variable value
And also in theese lines you have some mistakes:
int out=pop(arr);
std::cout<<pop<<"\n";
you must print "out" variable :
std::cout << out << "\n";
You can look to corrected code for your implementation in here :
https://repl.it/JaOd/0
I have this stack array code in C. You can use it as your guide in implementing it to C++.
#include <stdio.h>
#include <stdlib.h>
void push(void);
void pop(void);
int a[5];
int top = -1;
int counter = 0;
int choice;
main() {
do{
printf("*********************************************\nSTACK\nPress the
corresponding button you desire.\n\nPress 1 to push a number to
stack.\nPress 2 to display the current stack.\nPress 3 to pop the current
stack.\nPress 0 to exit.\n\n");
scanf("%d", &choice);
if(choice == 0){
choice = 0;
}
else if(choice == 1){
push();
}
else if(choice == 2){
int i;
printf("Current Stack:\n");
for(i = 0;i <= 4;i++){
printf("%d", a[i]);
}
printf("\n\n");
}
else if(choice == 3){
pop();
}
}while(choice != 0);
}
void push(){
if(top <= 3){
int input;
printf("Enter number to push: ");
scanf("%d", &input);
top = top + 1;
a[top] = input;
int i;
printf("Current Stack:\n");
for(i = 0;i <= 4;i++){
printf("%d", a[i]);
}
printf("\n\n");
}else{
printf("Out of Bounds\n\n");
exit(0);
}
}
void pop(){
if(top >= 0){
printf("You just popped: ");
printf("%d \n\n", a[top]);
a[top] = 0;
printf("Current Stack:\n");
int i;
for(i = 0;i <= 4;i++){
printf("%d", a[i]);
}
printf("\n\n");
top = top - 1;
}else{
printf("Out of Bounds\n\n");
exit(0);
}
}
#include <iostream>
int top;
void initialise_top(){
top=-1;}
bool stack_empty(int a[]){
if(top==-1)
return true;
else
return false;
}
void push(int a[],int x,int s){
if(top<s-1){
top=top+1;
a[top]=x;
}
else
std::cout<<"overflow"<<"\n";
}
int pop(int a[]){
if (stack_empty(a)==true)
std::cout<<"Underflow"<<"\n";
else{
--top;
return a[top+1];
}
}
void display(int a[]){
for(int i=0;i<=top;i++){
std::cout<<a[i]<<" ";
}
}
int main()
{
**initialise_top();**//this statement initialises top=-1
int arr[7];
//std::cout<<stack_empty(arr)<<"\n";
push(arr,15,7);
push(arr,6,7);
push(arr,2,7);
push(arr,9,7);
push(arr,17,7);
push(arr,3,7);
display(arr);
std::cout<<"\n";
int out=pop(arr);
std::cout<<**out**<<"\n";
return 0;
}
1.In your program the value of top=1 when the first element 15 is inserted. due
to this another value is shown for index 0.
So to have top=0, call the function initialise_top(); in main function.
2.To display 3 instead of 1 use
std::cout<<out<<"\n";
Modifications in the program are bold.
I have tried to improve my code. Please tell me if can improve.
#include <iostream>
#define max 1000
class Stack{
int top;
public:
int a[max];
Stack(){
top=-1;
}
bool stack_empty();
void push(int x);
int pop();
void display();
};
bool Stack::stack_empty(){
if(top==-1)
return true;
else
return false;
}
void Stack::push(int x){
int s=max-1;
if(top<s){
top=top+1;
a[top]=x;
}
else
std::cout<<"overflow"<<"\n";
}
int Stack::pop(){
if (stack_empty()==true)
std::cout<<"Underflow"<<"\n";
else{
--top;
return a[top+1];
}
}
void Stack::display(){
for(int i=0;i<=top;i++){
std::cout<<a[i]<<" ";
}
}
int main()
{
Stack stack1;
stack1.push(15);
stack1.push(6);
stack1.push(2);
stack1.push(9);
stack1.push(3);
stack1.display();
std::cout<<"\n";
std::cout<<stack1.pop()<<"\n";
stack1.display();
return 0;
}

Stack data structure array is not being recognized in functions

I have written C++ code for a stack. I am getting an error that array 'a' has not been declared in the scopes of push, pop and display functions. I have tried to remove private but the problem still persists. How can I fix this?
My code:
#include<iostream>
using namespace std;
class stack
{
private:
int n;
int a[10];
int top;
public:
stack(int n);
void push(int x);
int pop();
void display();
};
stack::stack(int q)
{
n=q;
top=-1;
}
void stack::push(int x)
{
if(top==n-1)
cout<<"\nStack overflow\n";
else
a[++top]=x;
}
int stack::pop()
{
if(top==-1)
cout<<"\nStack is empty\n";
else
return (a[top--]);
}
void stack::display()
{
int i;
for(i=top;i>=0;i--)
cout<<a[i]<<endl;
}
int main()
{
int n;
cout<<"\nEnter the size of stack\n";
cin>>n;
stack st(n);
int i,x;
while(1)
{
cout<<"\nSelect option 1.Push 2.Pop 3.Display\n";
cin>>i;
switch(i)
{
case 1: cin>>x;
st.push(x);
break;
case 2: st.pop();
break;
case 3: st.display();
break;
}
}
return 0;
}

pop() is not working properly

Here is a c++ code on stack.Ignore the extra code here
#include<iostream>
using namespace std;
class mystack
{
private:
int top;
int size;
int * s;
public:
void initialize()
{
top=-1;
cin>>size;
s=new int[size];
}
~mystack(){delete [] s;}
void push()
{
int x;
if(top==size-1)
cout<<"stack overflow!"<<endl;
else
{
cout<<"Enter element to be pushed:";
cin>>x;
top++;
s[top]=x;
cout<<s[top]<<endl;
}
}
int pop()
{
int p=s[top];
if(top==-1)
return 0;
else
{
top--;
return p;
}
}
int maxsize()
{
return size;
}
int isempty()
{
if(top==-1)
return 0;
else
return 1;
}
void display()
{
int i,p=top;
cout<<s[0]<<endl;
for(i=0;i<=p;i++)
cout<<s[i]<<endl;
}
};
int main()
{
int n,i;
cout<<"Enter no. of stacks:";
cin>>n;
mystack * st=new mystack[n];
for(i=0;i<n;i++)
{
cout<<"Enter size of stack "<<i+1<<":";
st[i].initialize();
}
int c,s;
while(1)
{
cout<<"*****Operations*****"<<endl;
cout<<"1.Push 2.Pop 3.Maxsize 4.isempty 5.Display 6.Quit"<<endl;
cout<<"Enter your choice:";
cin>>c;
if(n>1)
{
cout<<"Operation on which stack:";
cin>>s;
}
else
s=1;
if(c==1)
st[s-1].push();
else if(c==2)
{
if(st[s-1].pop()==0)
cout<<"stack underflow!"<<endl;
else
cout<<st[s-1].pop()<<endl;
}
else if(c==3)
cout<<st[s-1].maxsize()<<endl;
else if(c==4)
{
if(st[s-1].isempty()==0)
cout<<"True"<<endl;
else
cout<<"False"<<endl;
}
else if(c==5)
st[s-1].display();
else if(c==6)
break;
else
{
cout<<"Wrong input!"<<endl;
continue;
}
}
return 0;
}
Here accessing pop operation gives the element of top-1.I can't understand why.What should I do?When I do return s[top--] same thing is happening.
Since you haven't gotten back to this, I am going to presume you've already found your logic error.
So here is the one error I found. There may be more, I quit looking ...
In the following code, how many times is pop() being called?
else if(c==2)
{
if(st[s-1].pop()==0)
cout<<"stack underflow!"<<endl;
else
cout<<st[s-1].pop()<<endl;
}