STACK PUSH
POP IN C++
Write an algorithm for
Push and Pop operations
on Stack using Linked list
Task
Write
an algorithm for Push and Pop
operations on Stack using Linked list
Stack Using Linked List – C++
Algorithm
Node Structure
struct Node {
int data;
Node* next;
};
Stack Using Linked List – C++
Algorithm
Push Operation
Goal: Insert an element at the top of the stack.
void push(Node*& top, int value) {
Node* newNode = new Node(); // Create new
node
newNode->data = value; // Assign value
newNode->next = top; // Point to current top
top = newNode; // Update top
}
Stack Using Linked List – C++
Algorithm
Pop Operation
Goal: Remove and return the top element of the stack.
int pop(Node*& top) {
if (top == nullptr) {
cout << "Stack Underflow!" << endl;
return -1; // or throw an exception
}
int poppedValue = top->data;
Node* temp = top;
top = top->next; // Move top to next node
delete temp; // Free memory
return poppedValue;
}
Stack Using Linked List – C++
Algorithm
Example Usage
int main() {
Node* stackTop = nullptr;
push(stackTop, 10);
push(stackTop, 20);
push(stackTop, 30);
cout << "Popped: " << pop(stackTop) << endl; // 30
cout << "Popped: " << pop(stackTop) << endl; // 20
return 0;
}