Stack
Stack
isFull( ) Operation
int isFull( )
{
if(top = MAX-1)
return 1;
else
return 0;
}
Prepared by: Dr Deepak Gupta, CSED, MNNIT Allahabad, India
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;
5 10 5
15 10 5 10 5
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;
}
In case, we allocate a large amount of space for the stack, it will result in
sheer wastage of memory. Thus, there lies a tradeoff between the frequency
of overflows and the space allocated.
Stack A Stack B
#define MAX 50
int stack[MAX];
int topA = -1;
int topB = MAX;
• Function calls
• Recursion
• Tower of Hanoi
We have pushed the string “SPOT” on the stack and we get the reversed
string “TOPS”.
T O P S
T
O O O
P P P P P
S S S S S S S
• We can use stack to check the validity of an expression that uses nested
parentheses.
• An expression will be valid if it satisfies these two conditions:
– The total number of left parentheses should be equal to the total number of
right parentheses in the expression.
– For every right parentheses there should be a left parentheses of the same type.
• [A-B*(C+D)) Invalid
• (1+5} Invalid
• [5+4*(9-2)] Valid
• [A/(B+C)*D] Valid
[ A / (
(
[ [ [ [
B A- C )
( ( (
[ [ [ [
* D ]
[ [
#include <stdio.h> int check(char exp[ ])
#define MAX 30 {
int stack[MAX], top = -1; int I;
void push(char); char temp;
char pop(); for(i=0; i<strlen(exp); i++)
int match(char a, char b); {
main() if(exp[i] ==‘(‘ || exp[i] ==‘{‘ || exp[i] == ‘[‘)
{ push(exp[i]);
int valid; if(exp[i] ==‘)‘ || exp[i] ==‘}‘ || exp[i] == ‘]‘)
char exp[MAX]; if(top = = -1)
printf(“Enter an algebraic expression); {
gets(exp); printf(“Right parentheses are more than left\n)”
valid = check(exp); return 0;
if(valid = = 1) }
printf(“Valid expression”); else
else {
printf(“Invalid expression”); temp = pop( );
} if(!match(temp, exp[i]))
{
printf(“Mismatched parentheses are :”);
printf(“%c and %c\n”, temp, exp[i]);
return 0;
int match(char a, char b) }
{ }
if(a ==‘[‘ && b == ‘]’) }
return 1; if(top = -1)
if(a ==‘{‘ && b == ‘}’) {
return 1; printf(“Balanced Parentheses\n”);
if(a ==‘(‘ && b == ‘)’) return 1;
return 1; }
return 0; else
} {
printf(“left parentheses are more than right parentheses\n”);
return 0;
}
}