If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Here's a C++ implementation of stack operations 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; } void display() { Node* current = top; while (current) { std::cout << current->data << " "; current = current->next; } std::cout << std::endl; } }; 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); std::cout << "Stack elements: "; stack.display(); // Output: 4 2 1 stack.pop(); stack.pop(); stack.pop(); // Trying to pop more elements than present std::cout << "Stack elements: "; stack.display(); // Output: Stack is empty. 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.The
displaymethod is added to display the elements of the stack from top to bottom.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. We also display the elements of the stack at different stages. The output will show the elements being pushed, popped, and displayed.
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