Stack Operations Using Linked List
Creation:
Define a
Nodeclass withdataandnextattributes.Define a
Stackclass with atopattribute initialized toNone.
Push (insert an element to the top of the stack):
Create a new node with the given data.
Set the new node’s
nextattribute to the current top node.Update the
topattribute to the new node.
Pop (remove an element from the top of the stack):
Check if the stack is empty.
Store the data from the top node.
Update the
topattribute to the next node.Return the stored data.
IsEmpty (check if the stack is empty):
Return
Trueif thetopattribute isNone, otherwise returnFalse.
Dive into the world of data structures by implementing stack operations using linked lists in C. This guide walks you through the essential stack operations such as push, pop, peek, and checking if the stack is empty,
#include
#include
struct Node {
int data;
struct Node* next;
};
struct Node* top = NULL;
void push();
void pop();
void display();
int main() {
int choose;
while (1) {
printf("\nEnter Operation\n");
printf("1 for push operation\n");
printf("2 for pop operation\n");
printf("3 for display operation\n");
printf("4 for exit operation\n");
scanf("%d", &choose);
if (choose == 4) {
printf("You are exiting...\n");
break;
}
else if (choose == 1) {
push();
}
else if (choose == 2) {
pop();
}
else if (choose == 3) {
display();
}
else {
printf("Error, Enter a valid operation\n");
}
}
return 0;
}
void push() {
int x;
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Stack Overflow (Full)\n");
} else {
printf("Enter number to push: ");
scanf("%d", &x);
newNode->data = x;
newNode->next = top;
top = newNode;
}
}
void pop() {
if (top == NULL) {
printf("Stack Underflow (Empty)\n");
} else {
struct Node* temp = top;
printf("%d data is popped\n", top->data);
top = top->next;
free(temp);
}
}
void display() {
if (top == NULL) {
printf("Stack is Empty\n");
} else {
struct Node* temp = top;
printf("The elements in the stack are:\n");
while (temp != NULL) {
printf("%d\n", temp->data);
temp = temp->next;
}
}
}




