Here is the code..
//AIM: STACK USING LINK LIST
#include<stdio.h>
#include<stdlib.h>
typedef struct data
{ int info;
struct data *next;
} node;
void push(node **,int);
int pop(node **);
void traverse(node **);
void main()
{
node *temp = NULL;
int i,ch;
printf("1.PUSH\t2.POP\t3.DISPLAY\t4.exit\n");
while(1)
{
printf("Enter your choice\t");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter the value\t\t");
scanf("%d",&i);
push(&temp,i);
break;
case 2: i=pop(&temp);
printf("The value is %d\n",i);
break;
case 3: traverse(&temp);
break;
case 4:
exit(1);
default: printf("Try Again\n");
}
}
}
void push(node **tos,int item)
{
node *ptr;
ptr = (node *) malloc(sizeof(node));
if(ptr==NULL)
{ printf("Stack is full\n");
return;
}
ptr->info=item;
ptr->next=*tos;
*tos=ptr;
}
int pop(node **tos)
{
node *ptr;
int item;
if(*tos==NULL)
{ printf("Stack is empty\n");
return NULL;
}
ptr=*tos;
item=ptr->info;
*tos=(*tos)->next;
free(ptr);
return(item);
}
void traverse(node **tos)
{node *top;
top = *tos;
if(top==NULL)
{ printf("Stack is empty\n");
return;
}
while(top!=NULL)
{ printf("%d\t",top->info);
top=top->next;
}
printf("\n");
}
For Turbo C users.
//AIM: STACK USING LINK LIST
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<stdlib.h>
typedef struct data
{ int info;
struct data *next;
} node;
void push(node **,int);
int pop(node **);
void traverse(node **);
void main()
{
node *temp = NULL;
int i,ch;
clrscr();
printf("1.PUSH\t2.POP\t3.DISPLAY\t4.exit\n");
while(1)
{
printf("Enter your choice\t");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter the value\t\t");
scanf("%d",&i);
push(&temp,i);
break;
case 2: i=pop(&temp);
printf("The value is %d\n",i);
break;
case 3: traverse(&temp);
break;
case 4: getch();
exit(1);
default: printf("Try Again\n");
}
}
}
void push(node **tos,int item)
{
node *ptr;
ptr = (node *) malloc(sizeof(node));
if(ptr==NULL)
{ printf("Stack is full\n");
return;
}
ptr->info=item;
ptr->next=*tos;
*tos=ptr;
}
int pop(node **tos)
{
node *ptr;
int item;
if(*tos==NULL)
{ printf("Stack is empty\n");
return NULL;
}
ptr=*tos;
item=ptr->info;
*tos=(*tos)->next;
free(ptr);
return(item);
}
void traverse(node **tos)
{node *top;
top = *tos;
if(top==NULL)
{ printf("Stack is empty\n");
return;
}
while(top!=NULL)
{ printf("%d\t",top->info);
top=top->next;
}
printf("\n");
}
No comments:
Post a Comment