Header Ads Widget

C program on stack by using link list

 what is stack:- 

                         stack is a linear type of data structure which work on LIFO (Last in first out) principle. i.e. we can pop that item first which was inserted last. In stack there are two major operation  i.e push and pop.

PUSH:- push means insert the element into stack

POP:- pop means delete the element from the stack





what is link list:-   

                         A linked list is a linear data structure, in which the elements are store in random manner into memory. The elements in a linked list are linked using pointer .Address of the first node store in a pointer called HEAD ,    Every  node store the address of the next node.




code:-

       In this code we are insert the new element as first node of the list in push operation and in pop operation we delete the first node easily .

#include<stdio.h>
#include<stdlib.h>
int *stack=NULL;
struct node
{
int data;
struct node *link;
};

// function for the create list
struct node *createlist()
{
struct node *t;
t=(struct node*)malloc(sizeof(struct node));
return t;
}

// function for push the element in to stack
void push()
{
int element;
struct node *t;
t=createlist();
printf("Enter a element\n");
scanf("%d",&element);
t->data=element;
t->link=stack;
stack=t;
}

// function for pop the elelment from the stack
void pop()
{
struct node *t;
if(stack==NULL)
printf("Stack is underfow\n");
else
{
t=stack;
printf("%d is deleted from the stack\n",t->data);
stack=t->link;
}
}

// function for display the element of the stack
void display()
{
struct node *t;
if(stack==NULL)
printf("Stack is empty\n");
else
{
t=stack;
while(t!=NULL)
{
printf("%d ",t->data);
t=t->link;
}
printf("\n");
}
}

//Driver function
int main()
{
int ch;
printf("1. push the element in to the stack\n");
printf("2. pop the elelment fromt the stack\n");
printf("3.Display the element of the stack\n");
printf("4. exit\n");
while(1)
{
printf("enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: push();
break;
case 2: pop();
break;
case 3:display();
break;
case 4: exit(0);
default: printf("You entered the wrong key\n");
}
}
return 0;
}



Output:-


1. push the element into stack
2. pop the element from the stack
3. Display the element of the stack
4. exit
enter your choice
1
Enter a element
12
enter your choice
1
Enter a element
23
enter your choice
2
23 is deleted from the stack
enter your choice
1
Enter a element
32
enter your choice
3
32 12
enter your choice
4

Post a Comment

0 Comments