Reversing a stack in C++

I think that the simplest way to reverse a stack in C++ is to use some basic recursion to assign each element the address of its predecessor. The code goes as follows (building on this sample code)


	void Stack::reassign(Node* lastAddr, Node* target)
	{
		if(target)
		{
			reassign(target, target->_next);
			if(!target->_next)
				_top=target;
			target->_next=lastAddr;
		}

		
	}

	void Stack::reverse()
	{
		reassign((Node*)0, _top);
	}

It’s very short, but the inner working can be confusing. reverse() is publicly accessible and kicks the chain into motion. When reassign() is called it first checks to see if the node that you are trying to reassign exists, if not it breaks the recursion chain (otherwise it would run forever or crash). Next it calls itself with the next node in the list with a copy of it’s address so it can be linked back. When it gets to the end of the chain it assigns that node to the _top of the list. (I got stuck on this at first, without this the stack is simply the last node). As it works its way back to the surface it assigns the address of the node that originally called it to the _next property thus the list gets reversed. (Hopefully that makes sense, It’s kind of hard to explain)

Jesse Conner - October 8, 2013 - C++, Code