#include <stdio.h>
#include <stdlib.h>
// Node structure for stack
typedef struct Node {
int data;
struct Node* next;
} Node;
// Push function to add element to stack
void push(Node** top_ref, int new_data) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = new_data;
new_node->next = *top_ref;
*top_ref = new_node;
}
// Pop function to remove top element from stack
int pop(Node** top_ref) {
if (*top_ref == NULL) {
printf("Stack Underflow\n");
return -1; // Indicate empty stack
}
Node* temp = *top_ref; // Save top node
int popped = temp->data; // Save data to return
*top_ref = temp->next; // Move top to next node
free(temp); // Free old top node
return popped; // Return popped data
}
// Print stack from top to bottom
void printStack(Node* top) {
Node* current = top;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("null\n");
}
int main() {
Node* stack = NULL;
push(&stack, 1);
push(&stack, 2);
push(&stack, 3);
printf("Stack before pop: ");
printStack(stack);
int popped = pop(&stack);
printf("Popped element: %d\n", popped);
printf("Stack after pop: ");
printStack(stack);
return 0;
}
Check if stack is empty to avoid popping from empty stack
Node* temp = *top_ref; // Save top node
Save current top node to remove it safely
int popped = temp->data; // Save data to return
Store the data of the top node to return after removal
*top_ref = temp->next; // Move top to next node
Update top pointer to next node, effectively removing top
free(temp); // Free old top node
Free memory of removed node to avoid leaks
return popped; // Return popped data
Return the value popped from the stack
Stack before pop: 3 -> 2 -> 1 -> null
Popped element: 3
Stack after pop: 2 -> 1 -> null