/* stack using linked list */
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
void push(int);
void display();
int pop();
struct node *top=NULL;
int main()
{
push(10);
push(20);
push(30);
display();
pop();
display();
pop();
display();
pop();
display();
return 0;
}
void push(int d)
{
struct node *newnode;
newnode=(struct node *)malloc(sizeof(struct node));
if(newnode==NULL) printf("\nout of memory\n");
else
{
newnode->data=d;
newnode->next=top;
top=newnode;
}
}
int pop()
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
if(top==NULL)
{
printf("Under flow\n");
return -1;
}
else
{
temp=top;
//int info;
//info=top->data;
top=top->next;
if(temp!=NULL)
free(temp);
//return(info);
}
}
void display()
{
printf("\ndisplay callled:\n");
struct node *current;
if(top==NULL)
printf("\nstack empty\n");
else
{
current=top;
while(current)
{
printf("%d ",current->data);
current=current->next;
}
}
printf("\n");
}
/*
display callled:
30 20 10
display callled:
20 10
display callled:
10
display callled:
stack empty
*/
No comments:
Post a Comment