A C program to implement the stack using linked list is given below:
/* Program to implement stack as linked list*/
/* structure containing data part and linkpart */
struct node
{
int data ;
struct node *link ;
printf("The stack currently contains\n");
display ( s ) ;
i = pop ( &s ) ;
printf ( "\nItem popped: %d", i ) ;
i = pop ( &s ) ;
printf ( "\nItem popped: %d", i ) ;
i = pop ( &s ) ;
printf ( "\nItem popped: %d", i ) ;
printf("Stack after deleting three items\n");
display (s);
delstack ( &s ) ;
getch( ) ;
}
/* adds a new node to the stack as linked list */
void push ( struct node **top, int item )
{
struct node *temp ;
temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ;
if ( temp == NULL )
printf ( "\nStack is full." ) ;
temp -> data = item ;
temp -> link = *top ;
*top = temp ;
}
/* pops an element from the stack */
int pop ( struct node **top )
{
struct node *temp ;
int item ;
if ( *top == NULL )
{
printf ( "\nStack is empty." ) ;
return NULL ;
} temp = *top ;
item = temp -> data ;
*top = ( *top ) -> link ;
free ( temp ) ;
return item ;
}
/* displays the contents of the stack */
void display ( struct node *q )
{
printf ( "\n" ) ;
/* traverse the entire stack */
while ( q != NULL )
{
printf ( "%d ", q -> data ) ;
q = q -> link ;
}
}
/* deallocates memory */
void delstack ( struct node **top )
{
struct node *temp ;
if ( *top == NULL )
return ;
while ( *top != NULL )
{
temp = *top ;
*top = ( *top ) -> link ;
free ( temp ) ;
}
}