Implementation-of-stack-using-list-in-C-with-dataStructure
admin
#Implementation-of-stack-using-list-in-C-with-dataStructure
When it comes to implementing a stack in C, linked lists offer a dynamic and flexible alternative to arrays. This approach dynamically allocates memory, making it possible to avoid the fixed size limitations of array-based stacks. In this article, we’ll dive into the implementation of a stack using a linked list, explain the key operations, and highlight the advantages of using this approach.
A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. This means that the last element added to the stack is the first one to be removed. Stacks are widely used in various applications like function call management, expression evaluation, and backtracking.
Below is the C code for implementing a stack using a linked list:
#include<stdio.h>
#include<stdlib.h>
// Define the structure for a stack node
struct stack {
int no;
struct stack *next;
};
struct stack *top = NULL;
// Push operation
void push(int val) {
struct stack *n;
n = (struct stack *)malloc(sizeof(struct stack));
if (n == NULL) {
printf("\nStack Overflow\n");
return;
}
n->no = val;
n->next = top;
top = n;
printf("\nNode Pushed: %d\n", val);
}
// Pop operation
int pop() {
if (top == NULL) {
printf("\nStack Underflow\n");
return -999;
}
int val = top->no;
struct stack *temp = top;
top = top->next;
free(temp);
return val;
}
// Display stack
void show() {
if (top == NULL) {
printf("\nStack is Empty\n");
return;
}
struct stack *p = top;
printf("\nStack Elements: ");
while (p != NULL) {
printf("%d ", p->no);
p = p->next;
}
printf("\n");
}
// Main function
int main() {
int no, ch;
do {
printf("\n1. Push");
printf("\n2. Pop");
printf("\n3. Show");
printf("\n0. Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("\nEnter number to push: ");
scanf("%d", &no);
push(no);
break;
case 2:
no = pop();
if (no != -999)
printf("\nPopped: %d\n", no);
break;
case 3:
show();
break;
case 0:
printf("\nExiting...\n");
break;
default:
printf("\nInvalid choice\n");
}
} while (ch != 0);
return 0;
}
In this article, we explored how to implement a stack using a linked list in C, its key operations, and why linked lists are a superior choice over arrays for dynamic memory management. This approach ensures flexibility and efficient memory utilization, making it ideal for scenarios where stack size cannot be determined in advance.
For more programming tutorials and resources, visit DeveloperIndian.com and boost your knowledge of data structures and algorithms!