If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Below is the C++ implementation of a stack using a singly linked list:
cppCopy code
#include <iostream> class Node { public: int data; Node* next; Node(int data) : data(data), next(nullptr) {} }; class Stack { private: Node* top; public: Stack() : top(nullptr) {} ~Stack() { while (!isEmpty()) { pop(); } } bool isEmpty() { return top == nullptr; } void push(int value) { Node* newNode = new Node(value); newNode->next = top; top = newNode; } void pop() { if (isEmpty()) { std::cout << "Stack Underflow! Cannot pop element." << std::endl; return; } Node* temp = top; top = top->next; delete temp; } int peek() { if (isEmpty()) { std::cout << "Stack is empty. Cannot peek." << std::endl; return -1; } return top->data; } }; int main() { Stack stack; stack.push(1); stack.push(2); stack.push(3); std::cout << "Top element: " << stack.peek() << std::endl; // Output: 3 stack.pop(); stack.push(4); while (!stack.isEmpty()) { std::cout << "Popped element: " << stack.peek() << std::endl; stack.pop(); } return 0; }In this implementation, the
Nodeclass is used to represent each node in the singly linked list. TheStackclass uses thetoppointer to keep track of the top element of the stack.The
pushmethod adds an element to the top of the stack by creating a new node and updating thetoppointer. Thepopmethod removes the top element from the stack, and thepeekmethod returns the value of the top element without removing it.In the
mainfunction, we demonstrate how to use theStackclass by creating a stack. We push elements onto the stack, peek at the top element, and then pop elements until the stack becomes empty. The output will show the elements being pushed and popped, following the Last In First Out (LIFO) principle.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support