Inplace stack reversal(recursive)

This is a discussion on Inplace stack reversal(recursive) within the C++ Programming forums, part of the General Programming Boards category; Hi, We had an assignment to reverse a stack "in place" using recursion. The following member functions are available- IsFull(),IsEmpty(), ...

  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
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,761
    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-12-2006, 12:41 AM
  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, 03:12 PM
  5. Stack Program Here
    By Troll_King in forum C Programming
    Replies: 7
    Last Post: 10-15-2001, 06:36 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21