Stack Implementation Using Linked list in C
The stack implementation can be done by using linked list. This handles the dynamic memory location. It has a node and pointer.
The technical implementation is as follows...
code:
#include <stdio.h>
#include <stdlib.h>
struct l_Node {
int s_data;
struct l_Node*
l_next;
};
struct l_Node* s_top = NULL;
void s_push(int s_value) {
struct l_Node*
newNode = malloc(sizeof(struct l_Node));
newNode->s_data
= s_value;
newNode->l_next
= s_top;
s_top = newNode;
printf("Pushed %d to the stack\n", s_value);
}
int pop() {
if (s_top == NULL)
{
printf("The Stack is Underflow\n");
return -1;
}
int s_value =
s_top->s_data;
struct l_Node*
temp = s_top;
s_top =
s_top->l_next;
free(temp);
printf("Popped %d from the stack\n", s_value);
return s_value;
}
int peek() {
if (s_top == NULL)
{
printf("The Stack is empty\n");
return -1;
}
printf("The
Top element is %d\n", s_top->s_data);
return
s_top->s_data;
}
void display() {
struct l_Node*
temp = s_top;
printf("Stack
contents: ");
while (temp !=
NULL) {
printf("%d -> ", temp->s_data);
temp =
temp->l_next;
}
printf("NULL\n");
}
s_push(100);
s_push(220);
s_push(30);
s_push(23);
s_push(410);
peek();
display();
pop();
peek();
display();
return 0;
}
Output:
Pushed 100 to the stack
Pushed 220 to the stack
Pushed 30 to the stack
Pushed 23 to the stack
Pushed 410 to the stack
The Top element is 410
Stack contents: 410 -> 23 -> 30 -> 220 -> 100
-> NULL
Popped 410 from the stack
The Top element is 23
Stack contents: 23 -> 30 -> 220 -> 100 -> NULL
The above code implements the stack using linked list. Hope, this code is useful to you. Keep coding!!!
Comments
Post a Comment