Skip to content

Instantly share code, notes, and snippets.

@thecoducer
Last active August 30, 2017 14:11
Show Gist options
  • Save thecoducer/eeef32267550da62e42276c6390f83b0 to your computer and use it in GitHub Desktop.
Save thecoducer/eeef32267550da62e42276c6390f83b0 to your computer and use it in GitHub Desktop.
//Language:- C
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
int count=-1; //to count elements in stack
void main()
{
int choice, data, reply;
node *top;
top=NULL; //Empty Stack created
do
{
printf("\n1. Push an element onto stack.\n");
printf("2. Pop an element from stack.\n");
printf("3. Display current stack contents.\n");
printf("4. Exit.\n");
printf("\nEnter your choice:- ");
scanf("%d", &choice);
switch(choice)
{
case 1:
{
printf("\nEnter an integer element:- ");
scanf("%d", &data);
reply=push(data, &top);
if(reply==1)
printf("\nValue Pushed.\n");
else
printf("\nMemory Allocation Failed.\n");
break;
}
case 2:
{
reply=pop(&top);
if(reply==0)
printf("\nStack Underflows.\n");
else
printf("\nPopped Value is %d.\n", reply);
break;
}
case 3:
{
if(top==NULL)
{
printf("\nThe stack is empty\n");
break;
}
else
{
display(top);
break;
}
}
case 4:
exit(0);
default:
{
printf("\nInvalid Input. Try Again.\n");
break;
}
}
}while(1);
}
int push(int data, node **top)
{
node *temp;
temp=(node*)malloc(sizeof(node)); //to create a new room in stack
if(!temp)
return 0; //memory allocation failed
temp->data=data; //pushing given data
temp->next=*top;
*top=temp; //storing the address of the latest element in top
count++;
return 1; //value pushed
}
int pop(node **top)
{
node *temp;
int data;
if(*top==NULL)
return 0; //stack underflows
else
{
temp=*top;
*top=(*top)->next;
data=temp->data; //to show the popped value
free(temp); //deleting the node
count--;
return data;
}
}
void display(node *element)
{
int i=count;
while(element!=NULL)
{
printf("Element %d - %d\n", i--, element->data);
element=element->next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment