Solution:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct stack
{
int data;
struct stack * next;
};
struct stack *top=NULL;
struct stack *cn()
{
struct stack *n;
n=(struct stack *)malloc(sizeof(struct stack));
return (n);
}
void push()
{
struct stack *newnode;
int x;
printf("Enter element of stack :\n");
scanf("%d",&x);
if(top==NULL)
{
newnode=cn();
newnode->data=x;
newnode->next=NULL;
top=newnode;
}
else
{
newnode=cn();
newnode->data=x;
newnode->next=top;
top=newnode;
}
printf("Element pushed successfully.\n");
}
void pop()
{
int pop,flag=0,item;
struct stack *temp;
if(top==NULL)
{
printf("Stack is empty.\n");
}
else
{
temp=top;
temp->data=item;
top=top->next;
free(temp);
flag=1;
}
if(flag==1)
{
printf("Element popped successfully.\n");
}
}
void display()
{
struct stack *temp;
printf("\n");
if(top==NULL)
{
printf("Stack is empty.\n");
}
else
{
temp=top;
while(temp->next!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
printf("%d\n",temp->data);
}
}
void main()
{
int choice;
while(choice!=4)
{
printf("\n\n1. Push\n");
printf("2. Pop\n");
printf("3. Display\n");
printf("4. Exit\n\n");
scanf("%d",&choice);
switch(choice)
{
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
break;
default: printf("Enter a valid choice.\n");
}
}
}
0 Comments