Friday, August 27, 2010
C Program to implement linked list as a stack
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
sturct node
{
int data;
struct node *link;
};
void push(struct node**,int);
int pop(struct node**);
void delstack(struct node**);
void main()
{
struct node *s=NULL;
int i;
clrscr();
push(&s,10);
push(&s,19);
push(&s,1);
push(&s,20);
push(&s,32);
push(&s,16);
i=pop(&s);
printf(" \n Item popped : %d ",i);
i=pop(&s);
printf(" \n Item popped : %d ",i);
i=pop(&s);
printf(" \n Item popped : %d ",i);
delstack(&s);
getch();
}
/* Adds a new node to the stack as linked list */
void push(struct node **top,int item)
{
struct node*temp;
temp=(struct node*)malloc(sizeof(struct node));
if(temp==NULL)
printf("\n Stack is Full");
temp->data=item;
temp->link=*top;
*top=temp;
}
/*Pops an element from the stack */
int pop(struct node **top)
{
struct node *temp;
int temp;
if(*top==NULL)
{
printf("\n Stack is Empty ");
return NULL;
}
temp=*top;
item=temp->data;
*top=(*top)->link;
free(temp);
return item;
}
/* Deallocates memory */
void delstack(struct node **top)
{
struct node *temp;
if(*top==NULL)
return;
while(*top!==NULL)
{
temp=*top;
*top=(*top)->link;
free(temp);
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment