answersLogoWhite

0

The following function template will reverse any stack of type T:

template<typename T>

void reverse_stack (sd::stack<T>& A) // Pass by reference!

{

std::stack<T> B, C; // Two additional stacks (initially empty).

while (!A.empty()) { B.push (A.top()); A.pop(); }

while (!B.empty()) { C.push (B.top()); B.pop(); }

while (!C.empty()) { A.push (C.top()); C.pop(); }

// A is now in reverse order.

}

A more efficient method is to pop the stack onto a queue.

template<typename T>

void reverse_stack_optimised (sd::stack<T>& A) // pass by reference!

{

std::queue<T> B;

while (!A.empty()) { B.push_back (A.top()); A.pop(); }

while (!B.empty()) { A.push (B.front()); B.pop(); }

// A is now in reverse order.

}

User Avatar

Wiki User

10y ago

What else can I help you with?