73.9k views
0 votes
Create a class template Stack to implement all the Stack functions using a Stack Class.

Using the complete code with the stack operations, implement the following stack: assuming a stack with elements {1,6 9, 8, 0}, Output a re-arranged stack with element {8, 9, 6, 1, 0}

User Soleshoe
by
8.2k points

1 Answer

5 votes

Final answer:

The question involves implementing a stack class template in C++ that provides basic stack operations. A class with push, pop, top, is Empty, and display methods is showcased, and it can be used to re-arrange a stack as per the given requirement.

Step-by-step explanation:

Implementing a Stack Class in C++

To implement a stack with the required functionality, one needs to define the basic operations such as push, pop, and display. The following is an example of how one could implement a template class for a stack:

template
class Stack {
private:
std::vector elements;
public:
void push(T const& elem) {
elements.push_back(elem);
}
T pop() {
if (elements.empty()) throw std::out_of_range("Stack<>::pop(): empty stack");
T elem = elements.back();
elements.pop_back();
return elem;
}
T top() const {
if (elements.empty()) throw std::out_of_range("Stack<>::top(): empty stack");
return elements.back();
}
bool isEmpty() const {
return elements.empty();
}
void display() const {
for(auto it = elements.rbegin(); it != elements.rend(); ++it) {
std::cout << *it << '\\';
}
}
};
To achieve the desired re-arranged stack with elements {8, 9, 6, 1, 0}, one would push the elements onto a stack and then pop them to rearrange. This may also involve using additional stacks or other structures for temporary storage during the re-arrangement process.

User Juancki
by
9.1k points