Implement Stack using linked list in a easy way and perform basics problem.
Here is the source code of how you can implement a stack using Linked list and perform basics operation like push , pop, peek , is Empty , isFull , display. Please feel free to contact me(harshprasadaju@gmail.com) or comment below if you have any queries.
Thankyou.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data; //--> Defining a structure.
struct node *next;
};
int isEmpty(struct node *ptr) // --> here ptr is head or top.
{
if (ptr == NULL)
return 1;
return 0;
}
int isFull(struct node *pt1)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
if (ptr == NULL)
return 1;
return 0;
}
struct node *push(struct node *ptr, int item)
{
if (isFull(ptr))
printf("Stack Overflow.\n");
// return ptr;
else
{
struct node *s = (struct node *)malloc(sizeof(struct node));
s->data = item;
s->next = ptr;
ptr = s;
return ptr;
}
}
int pop(struct node **ptr)
{
int val;
if (isEmpty(*ptr))
{
printf("Stack underflow\n");
// return -1;
}
else
{
struct node *n = *ptr;
val = n->data;
*ptr = (*ptr)->next;
free(n);
return val;
}
}
void display(struct node *ptr)
{
struct node *temp = ptr;
printf("Displaying Elements of stack\n");
while (temp != 0)
{
printf("%d \n", temp->data);
temp = temp->next;
}
}
int main()
{
struct node *stack = NULL;
stack = push(stack, 97);
stack = push(stack, 57);
stack = push(stack, 77);
stack = push(stack, 70);
stack = push(stack, 67);
// stack = pop(stack);
printf("popped element is %d\n", pop(&stack));
display(stack);
return 0;
}
OUTPUT :
popped element is 67
Displaying Elements of stack
70
77
57
97
Comments
Post a Comment