GeeksforGeeks » Algorithms
Write a C Program to reverse a stack "in place" using recursion?
(13 posts)-
You can only use the following ADT functions on Stack:
IsEmpty
IsFull
Push
Pop
Top -
public void reverse(Stack st) { int m = (int)st.Pop(); if (st.Count != 1) reverse(st); Push(st , m); } public void Push(Stack st , int a) { int m = (int)st.Pop(); if (st.Count != 0) Push(st , a); else st.Push(a); st.Push(m); } -
void reverse(Stack *s){ if(s.IsEmpty()){ return; } m = s.Pop(); reverse(s); arrange(s,m); } void arrange(Stack *s,int m){ if(s.IsEmpty()){ s.push(m); return; } temp = s.Pop(); arrange(s,m); s.Push(temp); } -
@vibhanshu:
I guess...your code will not work (rather won't terminate) if stack has only one element...
Say "2" -
@krunal modi
The code posted by Vibhanshu will work even for one element in the stack as the condition to call the reverse method is if(st.count!=1) and here it wont even be called just it pop the element and push it back...
-
what is the program in C using recursion that would pop the value in stack??
-
@Manjusha Chava:
When stack has only one element say "3".
Vibhanshu's code is doing pop() first, because of that if(st.count != 1){} will get executed. Leading to infinite recursive call. -
***not a good practice!!!!*** but may work!
int *last = NULL; int reverse(Stack *s, int ix){ int tmp = Pop(s); if (s->size == 0){ int st = (&tmp - last) / ix; int *walk; for (walk = last; walk >= &tmp; walk += st){ Push(s, *walk); } return 0; } if (last == NULL) last = &tmp; return reverse(s, ++ix); } -
hope it will work fine
void reverse(stack s){ if(empty(s)){ return ; } func(s); k=s.pop(); reverse(s); push(&s,k); } void func(stack s){ if(empty(s)){ return ; } k=s.pop(); if(!empty(s)){ temp=s.pop(); push(&s,k); push(&s,temp); } else{ push(&s,k); } } -
suppose stack is
3
2
1now one easy recurrence is
1. remove top from the stack
2. reverse whole stack
3. push top of 1 to bottom of stackstep 3 can again be simple recursion
1. if stack is empty , push the top
2. if stack is not empty, pop the element and recurr
3. push the element popped in 2reverse(Stack S) { if(s.empty()) return; int top = S.pop(); reverse(S); pushCurrntTop(S, top); } void pushCurrntTop(Stack S, int top) { if(s.empty()) { S.push(top); return; } int el = S.pop(); pushCurrntTop(S, top); S.push(el); } -
what is the realtime application of this or it just for honing one's skills ?
-
I don't see any realtime application for this (atleast not in my knowledge).
However, one interesting thing, when we talk about having a solution "in place", are you free to use stack or heap space extensively for our cause? Isn't that a usage of space?Can someone explain "in place" ? From what I have read so far and understood, it is about NOT using any EXTRA data structure with a size of N, where N is the number of elements in the original problem.
Reply
You must log in to post.