Stack using linked list
1) Stack using Linked List
Aim
To implement stack operations (Push, Pop, Display) using singly linked list in C.
Objective
To understand dynamic memory allocation with linked lists.
To implement LIFO (Last In, First Out) principle.
Algorithm
Push:
Create a new node.
Insert new node at beginning.
Update top pointer.
Pop:
If stack empty, print underflow.
Else remove first node.
Update top pointer.
Display:
Traverse from top to NULL.
Print each node’s data.
Flowchart
C Code (Stack using Linked List)
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
int main() {
struct Node* top = NULL;
struct Node* temp;
int choice, item;
while (1) {
printf("\n--- Stack Menu (Linked List) ---\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
if (choice == 1) { // Push
printf("Enter item to push: ");
scanf("%d", &item);
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = item;
newNode->next = top;
top = newNode;
}
else if (choice == 2) { // Pop
if (top == NULL)
printf("Stack Underflow!\n");
else {
temp = top;
printf("Popped: %d\n", temp->data);
top = top->next;
free(temp);
}
}
else if (choice == 3) { // Display
if (top == NULL)
printf("Stack is Empty!\n");
else {
printf("Stack elements: ");
temp = top;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
}
else if (choice == 4) {
printf("Exiting...\n");
break;
}
else {
printf("Invalid choice!\n");
}
}
return 0;
}
Comments
Post a Comment