1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
#include <iostream> template<typename T> class Stack { public: Stack() : top(nullptr) {} ~Stack() { while (!isEmpty()) { pop(); } } void push(const T& value) { Node* newNode = new Node(value); newNode->next = top; top = newNode; std::cout << value << " pushed to stack" << std::endl; } void pop() { if (isEmpty()) { std::cout << "Stack is empty. Nothing to pop." << std::endl; return; } Node* temp = top; top = top->next; std::cout << temp->data << " popped from stack" << std::endl; delete temp; } T peek() const { if (isEmpty()) { throw std::runtime_error("Stack is empty."); } return top->data; } bool isEmpty() const { return top == nullptr; } void display() const { Node* current = top; if (isEmpty()) { std::cout << "Stack is empty." << std::endl; return; } std::cout << "Stack elements:" << std::endl; while (current != nullptr) { std::cout << current->data << std::endl; current = current->next; } } private: struct Node { T data; Node* next; Node(const T& value) : data(value), next(nullptr) {} }; Node* top; }; int main() { Stack<int> stack; stack.push(10); stack.push(20); stack.push(30); std::cout << "Top element is: " << stack.peek() << std::endl; stack.display(); stack.pop(); stack.pop(); std::cout << "Top element is: " << stack.peek() << std::endl; stack.display(); return 0; } |
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:
1g++ stack.cpp -o stack
1./stack
- Demonstrates the usage of the