In this post, we will implement the stack using link list. First we define a node for link list as below:
struct node{
int info;
struct node *next;
};
typedef struct node NODE;
In the above code info
hold the value stored in stack and next
is pointer to next node in the list. Push Operation:
Now we will implement the push operation on the stack above defined. Let us see the code for push operation:
void push(NODE **start, int n){
NODE *ptr = getNode();
ptr->info = n;
ptr->next = *start;
*start = ptr;
}
Pop Operation:
Now we will implement the pop operation on the stack above defined. Let us see the code for push operation:
int pop(NODE **start){
NODE *temp = *start;
int info;
if(*start == NULL){
printf("\nNo element exists in the stack\n");
}
else{
*start = (*start)->next;
info = temp->info;
free(temp);
return info;
}
}
Program to implement stack using link list:
Here is the complete implementation of stack using link list:
#include <stdio.h>
#include <malloc.h>
struct node{
int info;
struct node *next;
};
typedef struct node NODE;
NODE* getNode();
void push(NODE **, int);
int pop(NODE **);
void traverse(NODE **);
int main(){
NODE *top = NULL;
push(&top, 1);
push(&top, 2);
traverse(&top);
pop(&top);
traverse(&top);
pop(&top);
pop(&top);
return 0;
}
int pop(NODE **start){
NODE *temp = *start;
int info;
if(*start == NULL){
printf("\nNo element exists in the stack\n");
}
else{
*start = (*start)->next;
info = temp->info;
free(temp);
return info;
}
}
void push(NODE **start, int n){
NODE *ptr = getNode();
ptr->info = n;
ptr->next = *start;
*start = ptr;
}
void traverse(NODE **start){
NODE *temp;
temp = *start;
while(temp != NULL){
printf("%d ", temp->info);
temp = temp->next;
}
printf("\n");
}
NODE* getNode(){
return (NODE*) malloc(sizeof(NODE));
}
Comments
Post a Comment