Sunday, November 9, 2008

lab program 10

Write a C program using dynamic variables and pointers to construct a stack of integers using singly linked list to perform the following operations:
a.Push
b.Pop
c.Display
It must print appropriate messages for Stack overflow and empty.



#include"stdio.h" /* Including header files*/
#include"conio.h"
#include"stdlib.h"
#include"alloc.h"
#include"string.h"

struct node /* Structure template declaration*/
{
int data;
struct node *next;
};

typedef struct node *Node;
Node getnode(); /*function prototype*/
void freenode(Node);
Node insertf(int,Node);
Node delete_info(Node);
void display (Node);
int top=-1;
void main()
{
Node first=NULL;
int item,ch,choice;
clrscr();
do{
printf("\n1.PUSH\n2.POP\n3.DISPLAY\n4.exit\n");
printf("\n enter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nenter the items to be inserted:");
scanf("%d",&item);
first=insertf(item,first);
break;
case 2:

first=delete_info(first); /*delete function call*/
break;
case 3:
display(first); /*display function call*/
break;
case 4:
exit(0);
break;
}
printf("\n do you want to continue...(y/n)");
ch=getche();
}while(ch!='n');
getch();
}


Node getnode() /*getnode function defination*/
{
Node temp;
temp=(Node)malloc(sizeof(struct node));/*creating node using malloc function*/
return temp;
}

void freenode(Node p)
{
free(p); /*removing a node using free function*/
}

Node insertf(int item,Node first) /*insertf function defination*/
{
Node temp; /* pointer temp to type Node*/
temp=getnode();
top++;
temp->data=item;
temp->next=first;
first=temp;
return(first);
}


Node delete_info(Node first)
{
Node temp;
if(first==NULL)
{
printf("\nstack overflow");
}
else
{
top--;
temp=first;
first=first->next;
printf("\n deleted data is %d",temp->data);
freenode(temp);
}
return first;

}

void display(Node first)
{
Node temp;
if(first==NULL)
{
printf("\nstack is empty");
}
else
{
printf("\n stack status");
temp=first;
while(temp!=NULL)
{
printf("\n%d",temp->data);
temp=temp->next;
}
}
}

No comments:

Post a Comment