how to reverse a stack using recursion in C++ - c++

I am trying to reverse stack without using extra space through recursion. But unable to find my error.
Here is my code. It is printing the same stack again.
#include<iostream>
#include<stack>
using namespace std;
void insert( stack<int>& k , int j){
k.push(j);
}
void reverse(stack<int> &s){
if(s.empty()){
return;
}
int temp = s.top();
s.pop();
reverse(s);
insert(s,temp);
}
int main()
{
stack<int>s;
for( int i = 5;i>0;i--){
s.push(i);
}
reverse(s);
while(!s.empty()){
cout << s.top() << " ";
s.pop();
}
return 0;
}

Your insert() function is incorrect since you only push temp into the stack and once the stack is empty the value of temp will be 5 so 5 is pushed then 4 and so on. Hence the stack is filled in the same order. This insert() should work.
void insert( stack<int>& k , int j){
if(k.empty()){
k.push(j);
return;
}
int temp = k.top();
k.pop();
insert(k, j);
k.push(temp);
}
insert() just inserts j to the bottom of the stack.

Your recursivity is not correct. You remove the top, call the same function (reverse) recursively and then push it back on top. This does not change its position! The same applies to all elements recursively: they do not change their position. A pure recursive solution (without using another stack or any data structure like an array or a list) to your problem is impossible.

Related

Function that will leave the smallest occurrences at the bottom of stack

I am trying to write a stack so that all of the occurrences of the smallest element are at the bottom of the stack, while the order of the other elements stays the same. For example, if I have the stack [4,3,1,5,8,1,4] it will become [4,3,5,8,4,1,1], but my problem is that the order changes
so i will get something like this[4,5,3,4,8,1,1]
#include <iostream>
#include <stack>
using namespace std;
void minstack(stack<int> &s)
{
stack<int> t1,t2;
int count=0,min;
if(!s.empty())
{
while(!s.empty())
{
if(s.top() <min)
{ min=s.top();
count=0;
}
t1.push(s.top()); s.pop();
count++;
}
for(int i = 0 ; i<count;i++)
{
s.push(min);
}
while(!t1.empty())
{
if(t1.top()!=min);
{ s.push(t1.top());
}
t1.pop();
}
}
}
int main()
{
stack <int> s;
s.push(4);
s.push(3);
s.push(1);
s.push(5);
s.push(8);
s.push(1);
s.push(4);
minstack(s);
while(!s.empty())
{
cout<<s.top()<<" "; s.pop();
}
}
Here's an idea. First we'll need to find the smallest element of the stack. Define a temporary stack t. We'll now pop all elements one by one from s and push them into t. At the same time, keep track of the minimum value min and the number of times it has been encountered so far in the popping process in count. Once this is done, notice that you'll have the reverse order of elements in t and have min and count. Now we'll push count number of elements of value min back into s. Then start popping and pushing from t to s except for the elements which equal min.

Copy elements from queue to stack

I want to write a code that copies queue elements in to a stack, and this copied elements should be sorted in the stack.
i've written the code below:
#include <bits/stdc++.h>
using namespace std;
int main(){
int n,x;
queue<int> q;
stack<int> s;
cin >> n;
for(int i=0;i<n;i++){
cin >> x;
q.push(x);
}
while(!q.empty()){
if(s.empty()){
s.push(q.front());
q.pop();
}
else{
if(q.front()>=s.top()){
s.push(q.front());
q.pop();
}
else{
while(q.front()<s.top() && !s.empty()){
q.push(s.top());
s.pop();
}
}
}
}
while(!s.empty()){
cout << s.top() << " ";
s.pop();
}
return 0;
}
but for some test cases like:3 1 2 3,the code does not seem to work.
please help me to figure out the problem with my code.
Your code seems to have a logic error in your inner while loop. You test s.top() before you test for s.empty(), which is the wrong order. s.top() is invalid if s.empty() is true. However, the exercise can be resolved relatively easily as described below.
You can retrieve the underlying container of a container adapter using the following helper:
template <class ADAPTER>
typename ADAPTER::container_type & get_container (ADAPTER &a)
{
struct hack : ADAPTER {
static typename ADAPTER::container_type & get (ADAPTER &a) {
return a.*&hack::c;
}
};
return hack::get(a);
}
Then, after populating the queue, you can copy the contents directly to the stack's underlying container, and sort it.
auto &qc = get_container(q);
auto &sc = get_container(s);
sc.assign(qc.begin(), qc.end());
std::sort(sc.begin(), sc.end());
You have to do what is essentially a selection sort: go through the queue N times, each time selecting the largest element to push onto the stack. The general idea is:
queue = queue containing items
stack = new empty stack
while queue.count > 0
// push the first item from the queue onto the stack
stack.push(queue.pop())
count = queue.count
// for each item remaining in the queue
for (i = 0; i < queue.count; ++i)
// if the item from the queue is larger than what's on the stack,
// then remove the item from the stack and put it back in
// the queue. And put the item from the queue onto the stack.
if (queue.peek() > stack.peek())
queue.push(stack.pop())
stack.push(queue.pop())

Unable to access vector value by index

#include<iostream>
#include<vector>
using namespace std;
class Stack
{
public:
int top;
vector<int> v;
Stack(int size)
{
top=0;
cout<<"Enter the values"<<endl;
for(int i=0; i<size; i++)
{
int val;
cin>>val;
v.push_back(val);
top++;
}
}
void push(int val)
{
v.push_back(val);
top++;
}
int pop()
{
int x=v[top];
top--;
return x;
}
void disp()
{
for(int j=top; j<=0; j--)
cout<<v[j]<<' ';
}
};
int main()
{
Stack s(3);
int k=s.pop();
cout<<k;
return 0;
}
I am trying to learn the basics of OOP.
Here, my Stack constructor and push function are working fine, but there is a problem with the pop and disp functions.
I'm assuming that I am using an incorrect syntax to access the elements of a vector(maybe?). Can anyone tell me where I am going wrong?
Also, the value of k always comes out to be 0.
You can use the vector functions
int k = s.back();
s.pop_back();
cout << k;
more informationhttp://www.cplusplus.com/reference/vector/vector/back/
You have a off-by-one index error.
The way you have implemented your class, when there are N items in the stack, the value of top is N.
Hence, top is not a valid index to access the elements of v. You can use:
int pop()
{
int x=v[top-1];
top--;
return x;
}
or
int pop()
{
top--;
int x=v[top];
return x;
}
As some of the other answers say, you can use the built-in vector functions to do these things (see pop_back and back.
However, if you want to define your own, I would use the vector.at(index) function. Addressing the values with the index as you have works, but it doesn't do any bounds checking at() does. Which would solve your problem above where your index isn't correct for the zero-based indexing of a vector.

How to reverse print stack using recursion?

Please note that it is just reverse printing not reversing a stack
What I want to do is with the help of recursion print the stack i.e bottom to top printing.
I have tried myself but the result is not what I expected.My code looks like this.
#include <bits/stdc++.h>
using namespace std;
void print(stack<char>st){
if(st.empty()){return;}
st.pop();
print(st);
cout<<st.top();
}
int main() {
// Assume that I have stack already made....
print(st);
cout<<endl;
}
return 0;
}
Would anybody mind having pointing out my mistake ? Also when I pass stack by reference the results are unexpected.Thanks for support.
Why don't you store the st.top() at variable and print it later.
void print(stack<char>st)
{
if(st.empty())
{
return;
}
char top = st.top();
st.pop();
print(st);
cout<<top<<endl;
}
Let me explain you:-
Suppose, Your stack --> 0, 1
Here, Call Hierarchy
print({0, 1})
{
// stack after pop -- {0}
print({0})
}
print({0})
{
// stack after pop -- {}
print ({})
// here you want to print top of empty stack
// which gives the exception
}
pop is function get element to print like reverse
void printStack()
{
if(!isEmpty())
{
int temp = pop();
printStack();
printf(" %d ", temp);
push( temp);
}
}
int pop()
{
if (isEmpty())
printf("Stack is Empty...\n");
else {
st.top = st.top - 1;
return st.array[st.top+1];
}
}

Seg Fault C++, list, list.last

My code crashes at insert function (segmentation fault), it looks like 'List.last' behave as static but its not. Dont mind the rest of a code. I know the solution must be simple but it cracks my head. It was a long time science I coded anything
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
using namespace std;
typedef int elementtype, position ;
const int maxlength=10;
struct List
{
elementtype elements[maxlength];
elementtype last;
};
position END(List l)
{
return(l.last+1);
}
position First(List l)
{
if (l.last>=0)
return(l.last);
else
return(END(l));
}
position Next(position p,List l)
{
return(l.elements[p+1]);
}
position Previous(position p,List l)
{
return(l.elements[p-1]);
}
position Locate(elementtype x, List l)
{ int i;
for(i=0;i<=maxlength;i++)
{
if(x==l.elements[i])
return(i);
else
return(END(l));
}
}
elementtype Retrieve(position p, List l)
{
return(l.elements[p]);
}
bool Insert(int x, position p, List &l)
{
int i;
if(l.last-1==maxlength)
return(false);
else
if((p>=0)&&(p<=maxlength))
{l.last++;
for(i=l.last;i>p;i--)
l.elements[i+1]=l.elements[i];
l.elements[p]=x;
return(true);}
else return(false);
}
bool Delete(position p, List &l)
{
int i;
if(p>0||p<l.last){
l.elements[i]=l.elements[i+1];
l.last=l.last-1;
return(true);}
else
if(p=l.last){
l.last=l.last-1;
return(true);}
else
return(false);
}
void print(List l)
{
position i=First(l);
while (i!=END(l))
{
cout<< Retrieve(i,l);
i=Next(i,l);
}
cout<<("\n");
}
int main(){
List l;
l.last=-1;
Insert(100,First(l),l);
print (l);
cout<<l.elements[0];
for (int i=0; i<3;i++)
Insert(i,First(l),l);
print (l);
Insert (20,Previous(END(l),l) ,l);
print(l);
Delete( Locate(20,l),l);
print(l);
return 0;}
Here in your Locate function
for(i=0;i<=maxlength;i++)
you have a problem as you are allowing access of index 10 in an array of length 10. Change to
for(i=0;i<maxlength;i++)
similarly here in Insert
if((p>=0)&&(p<=maxlength))
allows later access of index 10 at this line
l.elements[p]=x;
Currently you are accessing elements beyond the array limits. If an array is of size x you cannot access array[x] as indices are zero based.
Using a debugger would help you identify this.
Apart from the changes suggested by #mathematician1975 , one basic error is in the
print(List)
method.
When the statement i=Next(i,l); executes , it fetches a value from the List.elements array, which initially contains random values. So what comes in the variable i is a random index for the array which seems to be generating the segmentation fault.