Explanation:
- Stack Class:
- Attributes:
top
: Pointer to the top node in the stack.
- Nested
Node
Structure:data
: Stores the value of the node.next
: Pointer to the next node in the stack.
- Methods:
Stack()
: Constructor initializes an empty stack.~Stack()
: Destructor deletes all nodes to free memory.push(const T& value)
: Adds a new element to the top of the stack.pop()
: Removes the top element of the stack. If the stack is empty, it prints a message.peek() const
: Returns the top element of the stack without removing it. Throws an exception if the stack is empty.isEmpty() const
: Checks if the stack is empty.display() const
: Displays all elements in the stack from top to bottom.
- Attributes:
- main Function:
- Demonstrates the usage of the
Stack
class. - Performs operations such as pushing elements, displaying the stack, popping elements, and checking the top element.
Compilation:
To compile the program, use:
- Demonstrates the usage of the