/* Stack Implementation using Linked Lists */
#include<stdio.h>
#include<stdlib.h>
/* Structure Declaration:
Structure for a Stack (Linked List Structure)
Requires two elements.
One Element member, holding the value that the stack is to be made of
One Self-Referring Pointer member for making it a Linked List - Stack. */
typedef struct stacklink
{
int element;
struct stacklink *next;
} top ;
typedef top stack;
/* Create:
Initializes the stack with a NULL value. */
void create(stack *s)
{
s=NULL;
}
/* Push:
Pushes (Inserts) a node into the Stack, using a new temporary node.
Stack's Push operation is done only on the top of the stack */
stack *push(stack *s)
{
int a=0;
stack *temp;
printf("\nEnter the element to push into the stack: ");
scanf("%d",&a);
temp = (stack *)malloc(sizeof(stack));
temp->element = a;
temp->next = s;
return temp;
}
/* Pop:
Pops (Deletes) the top-most element out of the Stack.
Also checks if the stack is empty or not and pops only when there is an element available. */
stack *pop(stack *s)
{
stack *temp;
if(s->next!=NULL)
{
temp = s;
printf("\nPopped element is: %d\n",temp->element);
s = s->next;
free(temp);
}
else
{
printf("\nNothing to Pop from the stack.\n");
}
return s;
}
/* Display:
Displays the Stack in a pictorial fashion.
A sample output of the stack via this would look like:
The List is:
4 -> 5 -> 6 -> NULL
Where, NULL represents the END of stack. For an empty stack too, it shows NULL. */
void display(stack *s)
{
int temp=1;
printf("\nThe Stack is:");
if(s->next==NULL)
{
printf("\b empty");
}
while(s->next!=NULL)
{
if(temp)
{
printf("\n");
temp=0;
}
printf("%d --> ",s->element);
s=s->next;
if(s->next==NULL)
{
printf("NULL");
break;
}
}
printf("\n");
}
/* Main Menu:
Displays a menu-based access system for various operations on the stack.
The menu looks like:
1. Create
2. Push
3. Pop
4. Display
5. Exit
Each item in the menu calls the appropriate functions of the Stack. */
int main()
{
int choice, key, loc,throw=0;
stack *temp;
while(1)
{
printf("\nStacks\n-------\n");
printf("1. Create\n2. Push\n3. Pop\n4. Display\n5. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
temp=(stack *)malloc(sizeof(stack));
create(temp);
printf("\nNULL Stack created\n");
throw=1;
break;
case 2:
if(throw==1)
{
temp=push(temp);
display(temp);
}
else
{
printf("\nCreate a stack first ..\n");
}
break;
case 3:
if(throw==1)
{
temp=pop(temp);
display(temp);
}
else
{
printf("\nCreate a stack first ..\n");
}
break;
case 4:
if(throw==1)
display(temp);
else
printf("\nCreate the stack first ..\n");
break;
case 5:
return 0;
default:
printf("\nInvalid choice ...\n");
}
}
}