0% found this document useful (0 votes)
17 views6 pages

Stack Operations Algorithm in C++

The document outlines an algorithm for implementing Push and Pop operations on a stack using a linked list in C++. It includes the structure for a Node, the implementation of the push function to insert elements at the top of the stack, and the pop function to remove and return the top element. An example usage in the main function demonstrates pushing and popping elements from the stack.

Uploaded by

venil ilavarasan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views6 pages

Stack Operations Algorithm in C++

The document outlines an algorithm for implementing Push and Pop operations on a stack using a linked list in C++. It includes the structure for a Node, the implementation of the push function to insert elements at the top of the stack, and the pop function to remove and return the top element. An example usage in the main function demonstrates pushing and popping elements from the stack.

Uploaded by

venil ilavarasan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

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;
}

You might also like