Mental Model
A stack removes the top item first, like taking the last plate from a stack of plates.
Analogy: Imagine a stack of plates; you always take the top plate off first when you need one.
Top -> [3] -> [2] -> [1] -> null
Top -> [3] -> [2] -> [1] -> null
Top -> [3] -> [2] -> [1] -> null
Top -> [2] -> [1] -> null
Top -> [2] -> [1] -> null
Top -> [2] -> [1] -> null Popped value: 3
#include <iostream> using namespace std; class Stack { private: struct Node { int data; Node* next; Node(int val) : data(val), next(nullptr) {} }; Node* top; public: Stack() : top(nullptr) {} void push(int val) { Node* newNode = new Node(val); newNode->next = top; // link new node to current top top = newNode; // update top to new node } int pop() { if (top == nullptr) { cout << "Stack is empty, cannot pop.\n"; return -1; // indicate empty stack } int val = top->data; // save top value Node* temp = top; // save top node top = top->next; // move top down delete temp; // free old top return val; // return popped value } void print() { Node* curr = top; cout << "Top -> "; while (curr != nullptr) { cout << "[" << curr->data << "] -> "; curr = curr->next; } cout << "null\n"; } }; int main() { Stack s; s.push(1); s.push(2); s.push(3); s.print(); int popped = s.pop(); s.print(); cout << "Popped value: " << popped << "\n"; return 0; }
newNode->next = top; // link new node to current toptop = newNode; // update top to new nodeif (top == nullptr) {int val = top->data; // save top valuetop = top->next; // move top downdelete temp; // free old topif (top == nullptr) {top = top->next; // move top down
pop() operation do in a stack?stk in C++ STL?pop() as stk.pop();.std::stack<int> stk; stk.push(10); stk.push(20); stk.pop(); std::cout << stk.top();
std::stack<int> stk; stk.pop(); stk.push(5);
1, 2, 3, 4 pushed in that order (1 at bottom, 4 at top), what will be the stack content after performing two pop() operations?Pass the test and this pattern moves unknown