Showing posts with label variable length stack. Show all posts
Showing posts with label variable length stack. Show all posts

Thursday, 16 March 2017

C program to implement stack using linked list

The linked list data structure is the best way to implement a variable-sized stack. The stack can grow in size till there is enough space in the memory to hold the data. The dynamic stack implementation is given in the following C program.

//Stack using Linked list
#include<stdio.h>
#include<conio.h>
struct node
{
struct node *next;
int data;
}*head,*temp;

void push()
{
struct node *newnode;
newnode=(struct node *)malloc(sizeof(struct node));
printf("Enter the data\t");
scanf("%d",&newnode->data);
if(head==NULL)
{
head=newnode;
head->next=NULL;
}
else
{
newnode->next=head;
head=newnode;
  }
}
void pop()
{
if(head==NULL)
{
printf("Empty stack\n");
}
else
{
printf("The popped element is ");
temp=head;
head=head->next;
printf("%d",temp->data);
free(temp);
}
}
void display()
{
if(head==NULL)
{
printf("Empty stack\n");
}
else
{
temp=head;
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;
}
}
}
main()
{
int ch;
void push();
void pop();
void display();

clrscr();
  do
  {
  printf("\n1.Push\n");
printf("2.Pop\n");
printf("3.Display\n");
printf("Enter the choice\t");
scanf("%d",&ch);
switch(ch)
{
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
default:exit(0);
}
}while(1);
}


/*
OUTPUT:
________
1.Push
2.Pop
3.Display
Enter the choice        1
Enter the data  1

1.Push
2.Pop
3.Display
Enter the choice        1
Enter the data  2

1.Push
2.Pop
3.Display
Enter the choice        3
2->1->

1.Push
2.Pop
3.Display
Enter the choice        2
The popped element is 2

1.Push
2.Pop
3.Display
Enter the choice        4

*/