UNIT - II - Stacks
UNIT - II - Stacks
UNIT - II - Stacks
UNIT – II
2.1. STACKS:
A Stack is a linear list in which all additions and deletions are restricted to one end called to
top.
It is also known as restrictive data structure.
If you insert a data series into a stack and then remove it, the order of the data is reversed.
Data input as {5,10,15,20} is removed as {20,15,10,5}
This reversing attribute is why stacks are known as the Last in First Out (LIFO) data
structure.
Any situation we can add or remove an object at the top is a stack.
If you want to remove any object other than the one at the top, you must first remove all
objects above it.
A graphic representation of stack is shown in fig.
Definition:
A stack is a last – in – first – out (LIFO) data structure in which all insertions and deletions are
restricted to one end, called the top.
a. Push:
Push adds an item at the top of the stack
After the push, the new item becomes the top
The only problem with this simple operation is that there is room for the new item
If there is not enough room, the stack is an overflow state and the item cannot be added.
Figure shows the push stack operation
1
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
b. Pop:
When we pop a stack, we remove the item at the top of the stack and return it to the user.
After removing the top item, the next older item in the stack becomes the top.
When the last item in the stack is deleted, the stack must be set to its empty state.
If pop is called when the stack is empty, it is in an underflow state.
The pop stack operation is shown in fig.
c. Stack top:
The stack top copies the item at the top of the stack; that is, it returns the data in top element
to the user but does not delete it.
This operation is nothing but as reading the stack top.
Stack top can also result in underflow if the stack is empty.
The stack top operation is shown in figure.
2
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
3
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
0 1 2 3 4 5 6 7
stack: 17 8
23 97 9 44
top = 3 or count = 4
If the bottom of the stack is at location 0, then an empty stack is represented by top = -1 or count =
0
To add (push) an element, either:
o Increment top and store the element in stack[top], or
o Store the element in stack[count] and increment count
b. Popping:
To remove (pop) an element, either:
o Get the element from stack[top] and decrement top, or
o Decrement count and get the element in stack[count]
After Popping,
0 1 2 3 4 5 6 7
stack: 17 8
23 97 9 44
top = 2 or count = 3
When you pop an element, do you just leave the “deleted” element sitting in the array?
The surprising answer is, “it depends” on language.
There are two stack errors that can occur:
o Underflow: trying to pop (or peek at) an empty stack
o Overflow: trying to push onto an already full stack
4
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
C Implementation:
Push operation:
int stack[MAX];
int top=-1;
void push(int ele)
{
if(top>MAX)
{
printf(“stack is full\n”);
exit(0);
}
stack[++top]=ele;
}
Pop operation:
void pop()
{
if(top==-1)
{
printf(“stack is empty\n”);
exit(0);
}
a=stack[top--];
printf(“the element popped is %d”,a);
}
Display elements in stack:
void display()
{
int k;
if(top==-1)
{
printf(“stack is empty\n”);
exit(0);
}
printf("\n\tElements present in the stack are:\n\t");
for(k=0;k<=top;k++)
printf("%d\t",stack[k]);
}
5
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
6
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
while(!emptystack())
{
dele=pop();
printf("%d\t",dele);
}
getch();
}
void push(int ele)
{
if(top==MAX-1)
{
printf("stack is full\n");
exit(0);
}
stkarr[++top]=ele;
}
int pop()
{
int dele;
if(top==-1)
{
printf("stack is empty\n");
exit(0);
}
return(stkarr[top--]);
}
int emptystack()
{
if(top==-1)
return 1;
else
return 0;
}
Output:
Enter the elements into the stack and press at last ^z
56789
The list of numbers reversed:
9 8 7 6 5
Convert decimal to binary:
The following simple code segment transfers a decimal number into a binary number:
1. read (number)
2. loop (number>0)
7
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
8
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
if(top==MAX-1)
{
printf("stack is full\n");
exit(0);
}
stkarr[++top]=ele;
}
int pop()
{
int dele;
if(top==-1)
{
printf("stack is empty\n");
exit(0);
}
return(stkarr[top--]);
}
int emptystack()
{
if(top==-1)
return 1;
else
return 0;
}
Output:
Enter an integer: 45
The binary number is: 101101
2.1.3.2. Postponement
A Stack can be useful when the application requires that the use of data be postponed for a
while.
Two stack postpone applications are:
1. infix to postfix transformation
2. Postfix expression evaluation
Infix to postfix transformation
Infix notation: Infix notation is the common arithmetic and logical formula notation, in
which operators are written infix-style between the operands they act on
E.g. A + B
Postfix notation: In Postfix notation, the operator comes after the Operand.
For example, the Infix expression A+B will be written as AB+ in its Postfix Notation.
Postfix is also called ‘Reverse Polish Notation’
9
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
One disadvantage with the infix notation is that we need to use parentheses to control the
evaluation of the operators.
In postfix notation we do not need parentheses.
Infix to postfix can be done in two ways:
o Manual transformation
o Algorithmic transformation
i) Manual Transformation:
The rules for manually converting infix to postfix expressions are as follows:
1. Fully parenthesize the expression using any explicit parentheses and the arithmetic precedence
– multiply and divide before add and subtract.
2. Change all infix notations in each parenthesis to postfix notation, starting from the innermost
expressions. Conversion to postfix notation is done by moving the operator to the location of
the expressions closing parenthesis.
3. Removing all parentheses
Example:
A+B*C
Step1 results in
(A+(B*C))
Step2 moves the multiply operator after c
(A (BC*)+)
and then moves the addition operator to between the last two closing parentheses. This change is
made because the closing parenthesis for the plus sign is the last parenthesis. We know have
( A ( B C *) + )
Finally , step 3 moves the parentheses
ABC*+
More complex example
This example is not only longer but it already has one set of parentheses to override the default
evaluation order.
( A + B) * C + D + E * F – G
Step1 adds parentheses
( ( ( ( ( A + B ) * C ) + D ) + ( E * F ) ) – G)
Step2 then moves the operators .
( ( ( ( ( A B + ) C * ) D + ) ( E F * ) + ) G -)
Step3 removes the parentheses.
AB+C*D+EF*+G–
ii) Algorithmic Transformation
The manual operation would be difficult to implement in a computer
Another technique is that we can easily implement with a stack.
Simple example:
A * B converts to A B *
We can read the operands and output them in order.
10
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
The problem becomes how to handle the multiply operator; we need to postpone putting it
in the output until we have read the right operand B.
In this case we push operator into a stack and, after the whole infix expression has been
read, pop the stack and put the operator in the postfix expression
Complex Expression:
A * B + C converts to A B * C +
If we were to simply put the operators into the stack as we did earlier and then pop them to
the postfix expression after all of the operands had been read, we would get the wrong
answer.
Some how we must pair the two operators with their correct operands.
One possible rule might be to postpone an operator only until we get another operator .
Then before we push the second operator, we could pop the first one and place it in the
output expression.
This logic works in this case, but it won’t for others.
Consider the following Example:
A + B * C Converts to A B C * +
Infix expression use a precedence rule to determine how to group the operands and
operators in an expression.
We can use the same rule to convert infix to postfix
When we need to push an operator into the stack, if its priority is higher than the operator
at the top of the stack, we go ahead and push it into the stack.
Conversely , if the operator at the top of the stack has a higher priority than the current
operator, it is popped and placed in the output expression. Using this rule with the above
expression, we would take the following actions:
1. Copy operand A to output expression
2. Push operator + into stack
3. Copy operand B to output expression
4. Push Operator * into stack (priority of * is higher than +.)
5. Copy operand C to output expression
6. Pop operator * and copy to output expression
7. Pop Operator + and copy to output expression
Priority
o Priority 2: * /
o Priority 1: + -
o Priority 0: (
11
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
Stage 2
Stage 3
Next token is * Since Stack is empty (top==NULL) it is pushed into the Stack
Stage 4
12
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
Stage 5
Stage 6
Next token, + is operator, We consider the precedence of top element in the Stack, ‘(‘. The
outgoing precedence of open parenthesis is the least (refer point 4. Above). So + gets pushed
into the Stack
Stage 7
13
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
Stage 8
Next token ), means that pop all the elements from Stack and append them to the output
expression till we read an opening parenthesis.
Stage 9
Next token, -, is an operator. The precedence of operator on the top of Stack ‘*‘ is more
than that of Minus. So we pop multiply and append it to output expression. Then push
minus in the Stack.
Stage 10
14
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
Stage 11
Next, we will insert the division operator into the Stack because its precedence is more than
that of minus.
Stage 12
Stage 13
The input Expression is complete now. So we pop the Stack and Append it to the Output
Expression as we pop it.
15
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
16
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
C Implementation
#include<stdio.h>
#include<conio.h>
#include <ctype.h>
#define SIZE 50
char s[SIZE];
int top=-1;
void push(char elem)
{
s[++top]=elem;
}
char pop()
{
return(s[top--]);
}
int pr(char elem)
{
switch(elem)
{
case '#': return 0;
case '(': return 1;
case '+':
case '-': return 2;
case '*':
case '/': return 3;
}
}
void main()
{
char infx[50],pofx[50],ch;
int i=0,k=0;
clrscr();
printf("\n\nRead the Infix Expression ? ");
scanf("%s",infx);
push('#');
while((ch=infx[i++])!='\0')
{
if( ch == '(') push(ch);
else
if( ch == ')')
{
while( s[top] != '(')
17
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
pofx[k++]=pop();
pop(); /* Remove ( */
}
else
if(isalnum(ch)) pofx[k++]=ch;
else
{ /* Operator */
while( pr(ch) <= pr(s[top]))
pofx[k++]=pop();
push(ch);
}
}
while( s[top] != '#')
pofx[k++]=pop();
pofx[k]='\0';
printf("\n\nGiven Infix Expn: %s Postfix Expn: %s\n",infx,pofx);
getch();
}
Output:
Read the infix expression?
(a+b)*(c-d)/e
Given Infix Expn: (a+b)*(c-d)/e Postfix Expn: ab+cd-*e/
18
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
19
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
+ 49 3 52 52
((A+
(B*C)/
D)-(E-
F))
Equivalent infix: A+ B * C / D– (E– F)
Ex: 43*67+5-+)
20
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
Evaluate the
expression
4*3 =12
Pus it into the
stack
21
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
6
Operand ‘7’ and
‘6’
Are popped
=13
Push it into the
stack
Operand ‘5’ push it
into the stack
Operands ‘5’
and ‘13’ are
popped
We get ‘8’
8
Operator ‘+’
20
22
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
20
Now , pop the
element till the
opening bracket
)
AND THE FINAL
ANSWRER IS
’20’
C Implementation
#include<stdio.h>
#include<conio.h>
#define SIZE 50
char s[SIZE];
int top=-1;
void push(char elem)
{
s[++top]=elem;
}
char pop()
{
return(s[top--]);
}
int cal(int elem1,char op,int elem2)
{
switch(op)
{
23
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
case '+':return(elem1+elem2);
case '-':return(elem1-elem2);
case '*':return(elem1*elem2);
case '/': return(elem1/elem2);
}
}
void main()
{
char pofx[50],ch;
int i=0,opnd2,opnd1,val;
clrscr();
printf("\n\nRead the Postfix Expression ? ");
scanf("%s",pofx);
while((ch=pofx[i++])!='\0')
{
if(isdigit(ch))
{
ch=pofx[i-1]-'0';
push(ch);
}
else
{
opnd2=pop();
opnd1=pop();
val=cal(opnd1,ch,opnd2);
push(val);
}
}
val=pop();
printf("the result of evaluation of postfix expression is:%d",val);
getch();
}
2.1.4. Other Applications:
Parsing
Parsing is any logic that breaks data into independent pieces for further processing
For ex, to translate a source program to machine language, a compiler must parse the program into
individual parts such as keywords, names and tokens.
One common programming problem is unmatched parentheses in an algebraic expression
When parentheses are unmatched, two types of errors can occur: Opening parenthesis can be
missing or the closing parenthesis can be missing
These two errors are shown in fig.
24
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
In algorithm, we parse a source program to ensure that all of the parentheses are properly paired
Algorithm: Parse parentheses
Algorithm parseParens
This algorithms reads a source program and parses it to make sure all opning – closing parentheses are
paired
1. loop (more data)
1. read (character)
2. if (opening parenthesis)
1. pushstack (stack, character)
3. else
1. if (closing parenthesis)
1. if (emptystack(stack))
1. print (error: closing parenthesis not matched)
2. else
1. popstack (stack)
3. end if
2. end if
4. end if
2. end loop
3. if (not emptystack (stack))
1. print (error: opening parenthesis not matched)
end parseParens
C Implementation
#include<stdio.h>
#include<conio.h>
#define SIZE 50
char s[SIZE];
int top=-1;
void push(char elem)
{
s[++top]=elem;
}
char pop()
{
return(s[top--]);
}
int emptystack()
{
if(top==-1)
25
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR
Data structures Lecture Notes Unit - II
return 1;
else
return 0;
}
void main()
{
char pofx[50],ch;
int i=0,x,j,opnd1,opnd2,val;
clrscr();
printf("\n\nRead the Postfix Expression ? ");
scanf("%s",pofx);
while((ch=pofx[i++])!='\0')
{
if(ch=='(')
push(ch);
else
if(ch==')')
{
if(emptystack())
printf("error:closing parenthesis is not matched\n");
else
{
pop();
}
}
}
if(!emptystack())
printf("error: opening parenthesis not matched\n");
getch();
}
Output:
Read the Postfix Expression?
((A+B)*c
error:opening parenthesis is not matched
26
Prepared by: G. B. Hima Bindu, Asst. Prof., Dept. of IT, SVCET, CTR