include
include
include
/* Definition of structure node */
typedef struct node
{
int data;
struct node *next;
} ;
/* Definition of push function */
void push(node **tos,int item)
{
node *temp;
temp=(node*)malloc(sizeof(node)); /* Dynamically create new node */
if(temp==NULL) /* If enough amount of memory is */
{ /* not available, the function malloc will */
printf("\n Error: Memory Space is not sufficient "); /* return NULL to temp */ getch();
return;
}
else /* otherwise*/
{
temp->data=item; /* put item into the data portion of node*/
temp->next=*tos; /*Add this node at the front of the stack */
*tos=temp; /* managed through linked list*/
}
} /*end of function push*/
/* Definition of pop function */
int pop(node **tos)
{
node *temp; temp=*tos; int item;
if(*tos==NULL)
return(NULL);
else
{
*tos=(*tos)->next; /* To pop an element from stack*/
item=temp->data; /* Eliminate the front node of the */ free(temp); /* stack managed through L.L*/
return (item);
}
} /*end of function pop*/
/* Definition of display function */
void display(node *tos)
{
node *temp=tos;
if(temp==NULL) /* verify whether the stack is empty*/
{
printf("\n Stack empty");
return;
}
else
{
while(temp!=NULL)
{
printf("\n%d",temp->data); /* display all of the values of the stack*/
temp=temp->next; /* from the front node to last node*/
}
}
} /*end of function display*/
/* Definition of main function */
void main()
{
int item, ch;
char choice='y'; node *p=NULL; do
{
clrscr();
printf("\t\t\t\t*****MENU*****");
printf("\n\t\t\t1. To PUSH an element");
printf("\n\t\t\t2. To POP an element");
printf("\n\t\t\t3. To DISPLAY the elements of stack");
printf("\n\t\t\t4. Exit");
printf("\n\n\n\t\t\t Enter your choice:-");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n Enter an element that you need to push ");
scanf("%d",&item); push(&p,item); break;
case 2:
item=pop(&p);
if(item!=NULL);
printf("\n Detected item is%d",item);
break;
case 3:
printf("\nThe elements of stack are");
display(p);
break;
case 4:
exit(0);
} /*switch closed */
printf("\n\n\t\t Do you need to run it again y/n");
scanf("%c",&choice);
}
while(choice=='y');
}
/*end of function main*/
Likewise, as we did in the implementation of stack through arrays, to know the working of this program, we executed it thrice & pushed 3 elements (10, 20, 30). After that we call the function display in the next run to make out the elements in the stack.
At first, we defined a structure called node. Each of nodes contains two portions, data & a pointer which keeps the address of the next node into the list. The Push function will add a node at the front of the linked list, while pop function will delete the node from the front of the linked list. There is no requirement to declare the size of the stack in advance as we have done in the program where in we implemented the stack by using arrays as we create nodes as well as delete them dynamically. The function display will print elements of the stack.