OneCompiler

Lab_6

75

#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
struct node {
int data;
struct node *link;
} *top,*p;
main() {
void push (int num);
void display();
int pop();
int
info,
clrscr();
choice;
while(1)
{
printf("\nstack
Operations:");
printf("\n 1. push:");
printf("\n 2. display:");
printf("\n 3. pop:");
printf("\n 4. exit:");
printf("\n enter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1 :printf("\n enter the element to be added");
scanf("%d",&info);
push(info);
break;
case 2 :printf("\n elements in the stack");
display();
break;
case 3 :info = pop();
if (info == -1)
printf("\n stack is empty");
else
printf("\n popped element is %d",info);
break;
case 4 :exit(0);
default: printf("\n error in choice");
}
}
}

void push (int num)
{
p = (struct node *) malloc(sizeof(struct node));
p->data = num;
p->link = NULL;
if (top == NULL)
top = p;
else
{
p->link = top;
top = p;
}
}

void display()
{
p = top;
if (p == NULL)
{
printf("\n stack is empty");
return;
}
while (p != NULL)
{
printf("\n %d",p->data);
p = p-> link;
}
}

int pop()
{
int n;
p = top;
if (p== NULL)
return(-1);
top = top->link;
n = p->data;
free(p);
return(n);
}