C Programming language

adplus-dvertising
Example of Dynamic Implementation of Stack (Linked List Implementation)
Previous Home Next

As we know apart from static implementation, the stacks can be implemented by using pointers as follows:

#include <stdio.h>
#include<conio.h>
#define<stdlib.h>
void push();
void pop();
void display();
struct stack
{
 int num;
 struct stack *next;
};
typedef struct stack stck;
stck *head==NULL;
stck *temp, first;
void main()
{
int choice;
char ch;
clrscr();
printf("Program for various operations on stack using arrays");
do
{
 printf("\n1. PUSH");
 printf("\n2. POP");
 printf("\n3. Display");
 printf("Enter your choice :");
 scanf("%d",&choice);
 switch(choice)
{
     case 1: push();
         break;
     case 2: pop();
         break;
     case 3: display();
         break;
 default : printf("\nwrong choice made");
    }
printf("\ndo you want to continue y/n");
fflush(stdin);
scanf("%c",&ch);
}
while ((char=='y')||(char=='Y'));
getch();
}
void push()
{
int info;
temp=(stck *)malloc(sizeof(stck));
printf("\nEnter the element in the  stack :");
scanf("%d",&info);
temp->num=info;
temp->next=NULL
if(head==NULL)
{
    printf("\nStack is empty");
head=temp;
}
else
{
     first=head;
 while(first!=NULL)
 first=first->next;
 first->next=temp;
    }
}
void pop()
{
if(head==NULL)
{
     printf("\n the stack is empty");
}
else
{
     temp=head;
 while(temp->next!=NULL)
{
     first=temp;
 temp=temp->next;
    }
     first->next=NULL;
 free(temp);
 }
}
void display()
{
 int i;
 if(head==NULL)
 printf("\n stack is empty");
 else
{
     temp=head;
 printf("\nThe status of the stack is :");
 while(temp!=NULL)
{
     printf("%d",temp->num);
    }
}
}
Previous Home Next