Thread: Inplace stack reversal(recursive)

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    84

    Inplace stack reversal(recursive)

    Hi,

    We had an assignment to reverse a stack "in place" using recursion. The following member functions are available- IsFull(),IsEmpty(), Push(),Pop(),Top(). I've been thinking about this for a long time but I just cant get it. Here is what I have -

    Code:
    void ReverseStack(Stack& intStack)
    {
    	if(intStack.IsEmpty())
    		return;
    	int temp = intStack.Pop();
    	ReverseStack(intStack);
    	intStack.Push(temp);
    }
    I know it is wrong and in effect clears the stack and then pushes them back in the same order. Can anyone give me any hints or tips on how to approach this ? any help will be appreciated, thanks!

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    You could reverse in place with a double ended queue. Reversing in place with a stack is already wrong because it's not really possible. As to why your code doesn't work, well stacks are usually LIFO, so try it where the first pop is the bottom of the new stack. You'll find that even implemented recursively it's the same as with a while.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. stack and pointer problem
    By ramaadhitia in forum C Programming
    Replies: 2
    Last Post: 09-11-2006, 11:41 PM
  2. Question about a stack using array of pointers
    By Ricochet in forum C++ Programming
    Replies: 6
    Last Post: 11-17-2003, 10:12 PM
  3. error trying to compile stack program
    By KristTlove in forum C++ Programming
    Replies: 2
    Last Post: 11-03-2003, 06:27 PM
  4. What am I doing wrong, stack?
    By TeenyTig in forum C Programming
    Replies: 2
    Last Post: 05-27-2002, 02:12 PM
  5. Stack Program Here
    By Troll_King in forum C Programming
    Replies: 7
    Last Post: 10-15-2001, 05:36 PM