Stack
Stack
isFull( ) Operation
int isFull( )
{
if(top = MAX-1)
return 1;
else
return 0;
}
isEmpty( ) Operation int isEmpty( )
{
if(top = -1)
return 1;
else
return 0;
}
• The main advantage of using a linked list over arrays is that it is possible to
implement a stack that can shrink or grow as much as needed.
struct node
{
int info;
struct node *link;
};
struct node *top = NULL;
(a) Empty Stack (b) Push 5 (c) Push 10
Top is NULL Top Top
5 10 5
15 10 5 10 5
5
Push Operation: The function push( ) would be similar to the function
addatbeg( ) of single linked list.
void push(int item)
{
struct node *tmp;
tmp = (struct node*)malloc(sizeof(struct node));
tmp -> info = item;
if(tmp = = NULL) /*Memory is full*/
{
printf(“Stack Overflow\n”);
return;
}
tmp->link = top;
top = tmp;
}
5 10 5
int pop( )
{ (e) Pop
struct node * tmp; Top 15
int item;
if(isEmpty())
{ 10 5
printf(“stack underflow”);
return;
} (f) Pop
tmp = top; Top 10
item = tmp->info;
top = top->1ink;
free(tmp);
5
return item;
}