Skip to content

Instantly share code, notes, and snippets.

@NeoHBz
Created January 3, 2022 06:39
Show Gist options
  • Save NeoHBz/5f17ce4ee800dc12900c8e93189e9e51 to your computer and use it in GitHub Desktop.
Save NeoHBz/5f17ce4ee800dc12900c8e93189e9e51 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;
void push(int data);
void pop();
void display();
void create();
void main()
{
int data, choice;
create();
while (1)
{
printf("\n\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Dipslay");
printf("\n Enter choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf(" Enter data : ");
scanf("%d", &data);
push(data);
break;
case 2:
pop();
break;
case 3:
display();
break;
default :
printf(" Wrong input, please choose 1, 2 or 3.");
break;
}
}
}
void create()
{
top = NULL;
}
void push(int data)
{
if (top == NULL)
{
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;
top->info = data;
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data;
top = temp;
}
}
void display()
{
top1 = top;
if (top1 == NULL)
{
printf("Empty");
return;
}
while (top1 != NULL)
{
printf("%d ", top1->info);
top1 = top1->ptr;
}
}
void pop()
{
top1 = top;
if (top1 == NULL)
{
printf("\n Error : Stack already empty, can't pop.");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment