In: Computer Science
How to write code for stack with singly linked list using C?
Please show examples for create, free, isempty, push, top, pop functions.
#Program
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
}*top=NULL;
void display()
{
struct node *p;
if(top==NULL)
printf("stack is empty\n");
else{
p=top;
while(p!=NULL)
{
printf("%d-->",p->data);
p=p->next;
}
printf("NULL\n");
}
}
void create()
{
struct node *temp;
int n,i;
printf("Enter number of values to create: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter value: ");
temp=(struct node *)malloc(sizeof(struct node));
scanf("%d",&temp->data);
temp->next=NULL;
if(top==NULL)
{
top=temp;
}
else
{
temp->next=top;
top=temp;
}
}
display();
}
void push()
{
struct node *temp;
int x;
printf("enter the data: ");
scanf("%d",&x);
temp=(struct node*)malloc(sizeof(struct node));
temp->data=x,temp->next=NULL;
if(top==NULL)
top=temp;
else
{
temp->next=top;
top=temp;
}
display();
}
void pop()
{
struct node *temp;
if(top==NULL)
printf("stack is empty\n");
else
{
temp=top;
top=top->next;
temp->next=NULL;
}
display();
}
void Free()
{
struct node *temp;
if(top==NULL)
printf("stack is empty\n");
else
{
temp=top;
top=top->next;
temp->next=NULL;
free(temp);
}
display();
}
void peek()
{
printf("Top = %d\n",top->data);
}
void isempty()
{
if(top==NULL)
printf("Stack is empty\n");
else
printf("Stack is not empty\n");
}
main()
{
int opt;
while(1){
printf("\n-----------\n");
printf("1.create()\n2.push()\n3.pop()\n4.peek()\n5.isempty()\n6.free()\n7.exit\n");
printf("-----------\n");
printf("Enter your option: ");
scanf("%d",&opt);
switch(opt)
{
case 1: create(); break;
case 2: push(); break;
case 3: pop(); break;
case 4: peek(); break;
case 5: isempty(); break;
case 6: Free(); break;
case 7: exit(0);
default: printf("wrong choice\n");
}
}
}
#if you have any queries please
comment