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];
}
}
Related
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.
I want to make a char stack implementation, but i think something is wrong with it because when i try to use it for my other function it does not word and library stack works. Can you help to find an issue:
using namespace std;
Stack::Stack(int size)
{
arr = new char[size];
capacity = size;
t = -1;
}
int Stack::size()
{
return (t + 1);
}
Stack::~Stack()
{
delete[] arr;
}
bool Stack::empty()
{
return size()==0;
}
void Stack::push(char x)
{
if (size()==capacity) {
cout<<"Push to full stack";
arr[++t]=x;
}
}
char Stack::pop()
{
if (empty()) {
cout<<"Pop from empty stack";
--t;
}
return 0;
}
char Stack::top()
{
if (!empty())
return arr[t];
else
cout<<"Top of the stack is empty";
return 0;
}
I want to make a char stack implementation, but i think something is wrong with it because when i try to use it for my other function it does not word and library stack works. Can you help to find an issue:
Thank you in advance!
I think you need to make some changes to the push and pop function for your Stack to work
In push, you should put arr[++t]=x; outside the if statement instead of inside as you want to add value to arr if the current size is less than its capacity instead of when it is equal
In pop, you should put arr[--t]; outside the if statement instead of inside as you want to remove and return the last value in the array if the stack is not empty. When it is empty, you should consider returning a default character such as the null terminator character \0. You should also want to use arr[t--] instead of arr[--t] as the last element is currently at t so you want it to evaluate arr[t] before decreasing its value (t--)
void Stack::push(char x)
{
if (size()==capacity) {
cout<<"Push to full stack";
return;
}
arr[++t]=x;
}
char Stack::pop()
{
if (empty()) {
cout<<"Pop from empty stack";
return '\0';
}
return arr[t--];
}
infix to posfix expresion where a+b is converted in ab+.
i have been staring at the code for hours and wondering why is not showing any output at all. i tried reviewing it by line to the best that i could and still could not figure it out why. can anyone point out where im wrong or is it my code does not make any sense at all. also, i am only allowed to use array and string.
#include<iostream>
using namespace std;
string stack; //initialize stack to contain operators
int top=-1;
void push(char a){ //add/push it to stack
top++;
stack[top] = a;
}
char pop(){ //delete/pop the stack
return stack[top--];
}
int order_operation(char a){ //the precedence priority
if(a=='+' || a=='-'){
return 1;
}
else if(a=='*' || a=='/'){
return 2;
}
else {
return 3;
}
}
int main(){
string infix,postfix;
cout<<"infix: ";
getline(cin,infix);
for(int x = 0; x<infix.length(); x++){ //scan the infix for operator
if(infix[x]=='-' || infix[x]=='+' ||infix[x]=='*' || infix[x]=='/'){
while(!stack.empty() && order_operation(stack[top])>=order_operation(infix[x])){ //if the stack is not empty and check the precedence
postfix+=stack[top]; //add it to postfix string
pop(); //pop the stack operator
}
push(infix[x]);
}
else{
postfix+=infix[x]; //add to postfix string if its operand
}
}
while(!stack.empty()){ //if the stack is not empty put it to posfix string
postfix+=stack[top];
pop();
}
cout<<postfix;
}
You need to add endl as stated by #Carcigenicate.
Your pop() method is incorrect. It should pop and return the actual value at the top of the stack, and it should not take an argument. At present you are corrupting the stack every time you pop it.
i wrote a simple c++ code in codeblocks and i implemented stack and graph classes for that with dynamic memory allocation.
my code works properly and gives correct output but at the end it shows ***.exe has stopped working error and shows "Process terminated with status -1073741819" in build log.
i tried GNU gdb 6.8 debugger and it couldn't find any errors.
this problem was made after imlementing stack class, so this is my code if it can helps solving problem:
class stack
{
vertex* d;
int end;
public:
stack()
{
end=0;
d=NULL;
}
void create(int n)
{
d=new vertex[n];
}
vertex top()
{
return d[end];
}
void push(vertex y)
{
end++;
d[end]=y;
}
vertex pop()
{
end--;
return d[end+1];
}
~stack()
{
if (d!=NULL)
delete d;
}
};
vertex class is also declared before stack.
for some inputs, debugger says "Program received signal SIGSEGV, Segmentation fault."
edit: main asked:
int main()
{
G graf;
graf.get();
stack tree;
tree.create(graf.q()-1);
int q=0;
int i=0;
int u=0;
while (u<graf.q()-1)
{
tree.push(graf.u[i]);
if (graf.u[i].r[0]->flag > 0 && graf.u[i].r[1]->flag > 0 && u>=q)
tree.pop();
else
{
u++;
if (graf.u[i].r[0]->flag==0)
q++;
if (graf.u[i].r[1]->flag==0)
q++;
graf.u[i].r[0]->flag++;
graf.u[i].r[1]->flag++;
cout << tree.top().r[0]->name << " - " << tree.top().r[1]->name << '\n';
}
i++;
}
return 0;
}
i even tried adding a cout just before return 0 and my text printed.
Your code is wrong:
void push(vertex y)
{
end++;
d[end]=y;
}
Should be:
void push(vertex y)
{
d[end]=y;
end++;
}
Else, first pushed item goes to position 1instead of position 0.
Moreover, stack::top() returns next item, not last pushed:
vertex top()
{
return d[end];
}
should be:
vertex top()
{
return d[end-1];
}
I'm pretty sure you seg fault is due to unallocated memory being accessed, add assertions to have the program notify you when something gets wrong, like that:
class stack
{
vertex* d;
int cur;
int capacity;
public:
stack()
{
cur=0;
capacity=0;
d=NULL;
}
void create(int n)
{
assert( d == NULL );
capacity = n;
d=new vertex[n];
}
vertex top()
{
assert( cur != 0 );
return d[cur-1];
}
void push(vertex y)
{
cur++;
assert( cur < capacity );
d[cur]=y;
}
vertex pop()
{
assert( cur > 0 );
cur--;
return d[cur+1];
}
~stack()
{
if ( d != NULL )
delete [] d;
}
};
Then, run again, you'll see where you get an assertion.
Finally, check vertex copy constructor works fine, because pushing/poping does a lot of vertexcopy, if there's something wrong here, it could cause seg fault.
OK, so I edited my code, but I still have two problems :
But here's my code first :
#include <iostream>
using namespace std;
struct stack
{
int data[5];
int top;
};
void push (int a, stack &S)
{
S.top++;
if (S.top<5)
{
S.data[S.top]=a;
}
else cout<<"Stack is full!!!"<<endl; S.top--;
}
int pop(stack &S)
{
if (S.top==-1)
{
cout<<"Stack is empty!"<<endl;
}
else
{
int temp=S.data[S.top];
S.data[S.top]=NULL;
S.top--;
return temp;
}
}
bool isEMPTY(stack &S)
{
if (S.top==-1)
return true;
else return false;
}
bool isFULL(stack &S)
{
if (S.top==5)
return true;
else return false;
}
int main()
{
stack S = { {}, -1 };
push(5,S); cout<<"5 is pushed \n"<<endl;
push(3,S); cout<<"3 is pushed \n"<<endl;
push(1,S); cout<<"1 is pushed \n"<<endl;
push(2,S); cout<<"2 is pushed \n"<<endl;
push(6,S); cout<<"6 is pushed \n"<<endl;
push(7,S); cout<<"7 is pushed \n"<<endl;
cout<<pop(S)<<"is popped\n"<<endl;
cout<<pop(S)<<"is popped\n"<<endl;
cout<<pop(S)<<"is popped\n"<<endl;
return 0;
}
So, the first problem is, when I pop I get a "Totally random value" and it's not like LIFO.
Second is, I actually intended on inserting 6 values, when I already had the max value = 5, so the output actually showed me the 6 values.
stack S;
Since stack is POD, the above line doesn't initialize the member top. As such, using an uninitialized top in push and pop functions invokes undefined behavior.
Write this:
stack S {}; //must be compiled in C++11 mode, else write : stack S = stack();
This value-initializes S and its members, which means, top is initialized to 0. The rest of the code may still have other problems, but at least you have fixed the issues with proper initialization. If you work with 0 as initial value of top, you've write the logic of push and pop accordingly!
Once you fix that, check the value of top before pushing and poping values from the stack, as the member array can have at most 5 elements, and you cannot pop more elements when it is empty. You must maintain these invariants.
I do not see where an object of type stack was created and how data member top was initialized.
Also take nto account that member function push does not check whether there is an attempt to add an item beyond the array.
You should define the object the following way
stack S = { {}, -1 };
else cout<<"Stack is full!!!"<<endl; S.top--;
is identical to :
else
{
cout<<"Stack is full!!!"<<endl;
}
S.top--;
as a general rule, try to avoid: writing if/else without curly brackets, and, avoid writing more then one line of code in the same line.
The mistake is:
stack s;//you define the local variable "s" without been intitialized.
push(5,s);//pass the uninlitialized "s" to the function "push",when debugging your code,"s.top" is not a expected "-1",but some value incredible~(often extreamly larger than 5),so your push operation failed!
stack S;
S.top = -1;
for(int i = 0; i < 5; i++)
{
S.data[i] = 0;
}