0% found this document useful (0 votes)
14 views10 pages

Stack

Uploaded by

wiekdowow
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views10 pages

Stack

Uploaded by

wiekdowow
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Notes On Algorithms and Data Structures

Stack
1. Introduction
Ordered list has time complexity for insertion, deletion and traversal operation O(n). search operation can be
performed in O(n) time (on unsorted list) or O(logn) time (on sorted list). Simple thought of putting some
restriction on insertion and deletion operations in a list will generate other data structures like stack and Queue.

Stack is a special type of linear list in which all insertions and deletions occur at one end, called the top. Stack is
also known as LIFO (last-in-first-out) structure. While this restriction makes stack less flexible than list, it also
makes stack efficient (for those operations they can do) and easy to implement. Many
push
applications require only the limited form of insert and remove operations that stack
pop
provides. Stack is used for many applications in computer science such as syntax parsing,
top memory management, reversing data, backtracking, recursion etc.Ordered list has time
complexity for insertion, deletion and treaversal operation O(n). serach operation can be
prformed in O(n) time (on unsorted list) or O(logn) time (on sorted list).
For Example: Web browsers store the addresses of recently visited sites on a stack, the
undo-mechanism in an editor, the function-call mechanism

Special terminologies are used for two basic operations associated with stack:
(a) "Push" is the term used to insert or add an element into a stack.
(b) "Pop" is the term used to delete or remove an element from a stack.
Apart from these operations, following operations can be performed on stack:
(i) Create a stack (ii) Check whether a stack is empty, (iii) Check whether a stack is full (iv) Initialize a stack (v)
Read a stack top (vi) Print the entire stack.
2.1 Implementation of Stack using Array
Stack is maintained by a linear array Stack; a variable top holds the information about the location of the top-
most element in the stack; and a variable SIZE gives the maximum number of elements that stack can hold.
Since an array is static in nature hence it has limited capacity to accommodate elements. In order to add new
element (i.e. Push) in the stack it is necessary to check, is there any free space in the array or not. If not, then this
condition is known as stack overflow. In order to delete element (i.e. Pop) from the stack it is necessary to check,
is there an element in the stack or not. If not, then this condition is known as stack underflow. No element in stack
means stack is empty
Upward growing Downward growing
stack stack
Variable top is moving in the array to indicate stack top. There
top are two possible ways to implement stack
SIZE-1 SIZE-1
1. Upward growing stack: Initially top is at lower end and it
.. .. moves in upward direction as and when element is inserted into
.. .. the stack. Here the stack is empty when top=0.
1 1 2. Downward growing stack: Initially top is at upper end and
0 0 it moves in downward direction as and when element is inserted
top
into the stack. Here the stack is empty when top=SIZE.

Let us implement upward growing stack using array.


Push operation: In order to insert an element in the stack, first check the condition for overflow, if it is not then
advance top to next location and place element at the location pointed by top. Initially the stack is empty and one
can push elements in the stack as long as there is a place in stack (no stack overflow). Figure shows push
operations performed on stack. Push operation is performed in constant time hence time complexity is O(1).

SIT,Nagpur
Notes On Algorithms and Data Structures

top
4 4 4 4 4 top 4 8
3 3 3 3 top 3 9 3 9
2 2 2 top 2 3 2 3 2 3
1 1 top 1 7 1 7 1 7 1 7
0 top 0 5 0 5 0 5 0 5 0 5
Initial 1.Push(5) 2.Push(7) 3.Push(3) 4.Push(9) 5.Push(8)
Stack Stack Stack Stack Stack Stack
6.Push(10) -- generates stack-overflow condition

Figure. Push operations on a stack of SIZE=5

Following is a code for Push operation.


# define SIZE 5
int Stack[SIZE], top= 0;

void Push(int data){


if (top == SIZE)
printf("\n Stack is full -- StackOverflow \n");
else{
Stack[top]=data;
top++;
}
}
Table shows run of the function Push:
Table. Run of function Push
Operation top Stack Action
0 Empty stack
Push(5) 0 1 Stack[0]=5 Insert 5 at 0th position
Push(7) 12 Stack[0]=5, Stack[1]=7 Insert 7 at 1st position
Push(3) 2 3 Stack[0]=5, Stack[1]=7, Stack[2]=3 Insert 3 at 2nd position
Push(9) 3 4 Stack[0]=5, Stack[1]=7, Stack[2]=3, Stack[3]=9 Insert 9 at 3rd position
Push(8) 4 5 Stack[0]=5, Stack[1]=7, Stack[2]=3, Stack[3]=9, Stack[4]=8 Insert 8 at 4th position
Push(10) 5 Stack[0]=5, Stack[1]=7, Stack[2]=3, Stack[3]=9, Stack[4]=8 Stack overflow

Pop operation: Deletion of element from a stack is only possible if stack contains elements otherwise stack-
underflow condition occurs. If stack contains elements then element inserted last will be deleted first.
Implementation of Push suggests that element inserted last is at location top. In order to pop element from a stack,
check stack-underflow condition first, if it is not then process (or delete) element at top and decrement top. Figure
shows pop operations performed on stack Pop operation is performed in constant time hence time complexity is
O(1).
top
4 8 4 top 4 4 4 4
3 9 3 9 3 top 3 3 3
2 3 2 3 2 3 2 top 2 2
1 7 1 7 1 7 1 7 1 top 1
0 5 0 5 0 5 0 5 0 5 0 top
Initial 1.Pop() 2.Pop() 3.Pop() 4.Pop() 5.Pop()
Stack Stack Stack Stack Stack
6.Pop() -- generates stack-underflow condition Stack

SIT,Nagpur
Notes On Algorithms and Data Structures

Figure 2.7. Pop operations on a stack of SIZE=5

Following is a code for operation Pop


int Pop()
{
int val;

if(top == 0)
printf(" \n stack is empty -- StackUnderflow\n ");
else{
top--;
val = Stack[top];
return (val);
}
}
Table shows run of the function Pop:
Table . Run of function Pop
Operation top Stack Action
5 Stack[0]=5, Stack[1]=7, Stack[2]=3, Stack[3]=9, Stack[4]=8
Pop() 54 Stack[0]=5, Stack[1]=7, Stack[2]=3, Stack[3]=9 Delete element from 4th position
Pop() 43 Stack[0]=5, Stack[1]=7, Stack[2]=3 Delete element from 3rd position
Pop() 32 Stack[0]=5, Stack[1]=7 Delete element from 2 nd position
Push(4) 2 3 Stack[0]=5, Stack[1]=7, Stack[2]=4 Insert 4 at 2nd position
Pop() 3 2 Stack[0]=5, Stack[1]=7 Delete element from 2 nd position
Pop() 2 1 Stack[0]=5 Delete element from 1st position
Pop() 1 0 Delete element from 0th position
Pop() 0 Stack-underflow

Traversal operation: Processing of each element in stack can be done by either start from the top and reach up
to the bottom of the stack or start from the bottom of the stack and reach to the top of the stack. Following is a
code for traversal operation.
void Traverse()
{
int i;

if(top == 0)
printf(" \n stack is empty\n ");
else {
for(i=top-1; i>=0; i--)
printf("%d\t", Stack[i]);
}
printf("\n");
}
OR
void Traverse()
{
int i;

if(top = = 0)
printf(" \n stack is empty\n ");
SIT,Nagpur
Notes On Algorithms and Data Structures

else
{
for(i=top-1; i>=0; i--)
printf(“%d\n”, Stack[i]);
}
}

Exercise:
1. Write a function to implement
(i) Check whether a stack is empty or not
(ii) Check whether a stack is full or not
(iii) Read a stack top
2. Give implementation of downward growing stack using array.
3. A letter means push and an asterisk means pop in the following sequence. Give the sequence of values
returned by the pop operations when this sequence of operations is performed on an initially empty stack.
EAS*Y*QUE***ST***IO*N***
4. Write a program that reads in a positive integer and prints the binary representation of that integer.
5. Suppose you have a stack in which the values 1 through 5 must be pushed on the stack in that order, but
that an item on the stack can be popped at any time. Give a sequence of push and pop operations such that
the values are popped in the following order:
(a) 2, 4, 5, 3, 1
(b) 1, 5, 4, 3, 2
(c) 1, 3, 5, 4, 2.
6. Prove or disprove: All permutations of 1,2,...,n can be generated by a suitable sequence of such push and
pop operations.
7. Modify the array implementation of a stack so that the top will always be the first position of the array.
Compare its running time with the standard implementation.
8. Extend the specification of stack to include a function called searchstack that searches for a given element
on a stack and returns its position in relation with the top.
9. Extend the specification of stack to include a function called extractfromstack that searches and returns an
element e from a stack.
10. Write a program that checks whether an input string is a palindrome or not using a stack.
11. Write a program to test for balanced parentheses in an expressions using a stack
12. How many extra stacks are required to reverse the order of the stack elements in the same stack? Write an
algorithm to reverse the order of the stack elements and comment on time complexity of the operation.
13. Consider the following sequence of stack operation on empty stack:
push(a), push(b), push(c), pop(), push(d), push(e), pop(), pop(), pop(), pop().
(a) What is the order in which the elements are popped?
(b) Change the position of the pop() commands in the above sequence so that the items are popped in the
following order: b,d,c,a,e. You are not allowed to change the ordering of the push commands.
14. Consider the following sequence of stack operations:
push(d), push(h), pop(), push(f), push(s), pop(), pop(), push(m).
Assume the stack is initially empty, what is the sequence of popped values, and what is the final state of
the stack?
15. Implement a stack S of n elements using arrays. Write functions to perform PUSH and POP operations.
Implement queries using push and pop functions to
a. Retrieve the mth element of the stack S from the top (m < n), leaving the stack without its top m – 1
elements.
SIT,Nagpur
Notes On Algorithms and Data Structures

b. Retain only the elements in the odd positions in the stack and pop out all elements at even positions.
16. (a)Generate all permutations of 1, 2, 3 by a suitable sequence of such push and pop operations. All possible
permutations for 1, 2, 3 is as follows
1,2,3; 1,3,2; 2,1,3; 2,3,1; 3,1,2; 3,2,1
For example following sequence of push and pop operations generate permutation 3, 2, 1.
push(1), push(2), push(3), pop(), pop(), pop()
(b)If values are pushed in sequence 1, 2, 3 on the stack in that order, but item on the stack can be popped at
any time then how many permutations can be generated?

2.2 Using a Stack to Evaluate an Expression


Expression comprises of operators and operands. Operand is data or representation of data on which operation is
to be performed. Every operator is having arity (number of operands required to perform operation), priority
(precedence over the other operators) and associatively (order of evaluation from Left to right or right to left).
Unary operator requires one operand and while writing expression, operator can be preceded (i.e. prefix) or
followed by operand (i.e. postfix). For example –a, a-
Binary operator requires two operands and there are three possible notations to write expression
 Infix notation: operator is between operands (Operand1 op Operand2)
 Prefix or Polish notation: operator is before operands (op Operand1 Operand2)
 Postfix or reverse Polish notation: operator is after operands (Operand1 Operand2 op)
For Example:
Infix: A + B - C
Prefix: -+ABC
Postfix: AB+C-
Note: one of the usages of parenthesis in expression is to override the rules of priority and precedence of operators.
Parentheses may be written in nested form. Expression enclosed in innermost parentheses will be evaluated first.
For better understanding of expression sometimes parentheses are used in expression to depict the priority and
associatively of operators.
Infix notation is how expressions are written and recognized by humans and, generally, input to programs.
Advantages of postfix and prefix notations are
1. The need for parentheses is eliminated
2. The precedence rule is no longer relevant
3. The expression is evaluated by making
 left to right scan for postfix
 right to left scan for prefix

An arithmetic expression evaluation will have two steps:


1. To convert an infix expression to a postfix expression.
2. To evaluate the postfix expression that resulted from step 1.

Transformation of an infix expression to postfix or prefix notation


General rules for conversion of infix expression to postfix or prefix expression are:
1. Completely parenthesize the infix expression according to the order of precedence to specify the order of
operation.
2. Move each operator to its corresponding right (for postfix) or left (for prefix) parentheses.
3. Remove all parentheses
Following figure shows conversion of infix expression to postfix expression.

SIT,Nagpur
Notes On Algorithms and Data Structures

1. Given Infix expression: A/B^C+D*E-A*C


2. Parenthesise expression based on priority of operators Operators priority
(((A/(B^C))+(D*E))-(A*C)) ^ highest
3. Replace each right parenthesis with corresponding operator *,/
( ( ( A / (B ^ C ) ) + (D * E ) ) - (A * C ) ) +,- lowest

( ( ( A (B C ^ / (D E * + (A C * -
4. Removal of all left parentheses results in postfix expression
ABC^/D E*+A C*-

Figure. Infix expression to Postfix expression conversion

Following figure shows conversion of infix expression to prefix expression.

1. Given Infix expression: A/B^C+D*E-A*C


2. Parenthesise expression based on priority of operators Operators priority
(((A/(B^C))+(D*E))-(A*C)) ^ highest
3. Replace each left parenthesis with corresponding operator *,/
( ( ( A / (B ^ C ) ) + (D * E ) ) - (A * C ) ) +,- lowest

-+/A^B C))*D E))*A C))


4. Removal of all right parentheses results in prefix expression
-+/A^BC*D E*A C

Figure Infix expression to Prefix expression conversion

The problem with this conversion method is that it requires two passes: the 1st one reads the expression and
parenthesizes it while the 2nd actually moves the operators. It is observed that the order of operands is same in
infix and postfix notations. So first scan of an infix expression can form the postfix expression by immediately
passing operands to the output. Then it is just a matter of handling the operators. The solution is to store them in
stack until just the right moment and then unstack & pass them to output.
Infix expression contain tokens in the form of operands, operators & parentheses. Let us implement the above
scheme on in fix expression A + B * C

Token Decision Stack Output


none empty none
A Operand: pass A to output empty A
+ Operator : Since stack is empty, Push (‘+’) + A
B Operand: pass B to output + AB
*

Since stack contain operators and token is also operator hence as per scheme, * need to be pushed into stack but
there are two possibilities based on the priority of incoming operator and priority of operator on the top of the
stack
a. Push * in the stack, so +, * are operators in stack with * in the top.
b. Pop + from the stack and push * in the stack
Since priority of * is greater than priority of + hence * is pushed into stack
SIT,Nagpur
Notes On Algorithms and Data Structures

Token Decision Stack Output


* Operator : Since Priority(*) > Priority(+), Push (‘*’) +* AB
C Operand: pass C to output +* ABC
End of expression: pop all operators from stack & pass to output empty ABC*+

Sub-expression enclosed in parentheses overrides the rule of priority and associatively of operators used in
expression. Let us consider another example A * (B + C) / D.

Token Decision Stack Output


none empty none
A Operand: pass A to output empty A
* Operator : Since stack is empty, Push(‘ +’) * A
( Left parenthesis: Push(‘(‘) *( A
B Operand: pass B to output *( AB
+
Since simple priority rule will not yield correct postfix expression. Hence there is a need to define two separate
priorities for each operator when it is an in-coming (token) operator or it is an operator on the top of the stack.

Operator In-stack priority (isp) In-coming priority (icp)


) - -
^ 3 3
*, / 2 2
+, - 1 1
( 0 4

Now the rule is operators are taken out of the stack as long as their in-stack priority (isp) is greater than or equal
to the in-coming priority (icp) of the token operator.

Token Decision and action Stack Output


+ Operator: isp(‘(’) < icp(‘+‘), Push (‘+’) * (+ AB
C Operand: pass B to output *(+ ABC
) Right Parenthesis: Pop operators from stack & pass to output till * ABC+
one get matching left parenthesis on top of the stack. Delete left
parenthesis from stack and discard right parenthesis.
/ Operator: isp(‘*’) = icp(‘/‘), Pop() and Push (‘/’) / ABC+*
D Operand: pass D to output / ABC+*D
End of expression: pop all operators from stack & pass to output empty ABC+*D/

Let E is an arithmetic expression in infix notation and P is an equivalent postfix expression. The new expression
P will not contain any parentheses. During transformation of infix expression to postfix expression, stack is used
to store left parenthesis or the symbol for an operation. Initially empty stack is empty and expression E is scanned
from left to right.

Algorithm: to convert infix expression to postfix expression


While (not reached the end of E)
{
Read token;
If (token is an operand)
Add it to P;
If (token is left parenthesis)
Push it onto the stack;
If (token is right parenthesis)
SIT,Nagpur
Notes On Algorithms and Data Structures

{
While (the stack is not empty AND the top item is not a left parenthesis)
Pop the stack and add the popped value to P;
Pop the left parenthesis from the stack and discard it;
}
If (token is operator)
{
If (the stack is empty or if the top element is a left parenthesis)
Push the operator onto the stack;
Else
{
While (the stack is not empty AND the top of the stack is not a left parenthesis AND isp(Stack[top])
>= icp(token))
Pop the stack and add the top value to P;
Push the token (operator) onto the stack;
}
}
}
While (the stack is not empty)
Pop the stack and add the popped value to P;

Notes: At the end, if there is still a left parenthesis at the top of the stack, or if one find a right parenthesis when
the stack is empty, then E contained unbalanced parentheses and is in error.
Let us use the algorithm to convert infix expression (E): A + B * (C * D - E / F) / G – H to postfix expression (P)

Token Decision Stack Postfix Exp (P)


A Operand: add A to P A
+ Operator: stack is empty, Push (‘+’) + A
B Operand: add B to P + AB
* Operator: isp(‘+’) < icp(‘*‘), Push (‘*’) +* AB
( Left Parenthesis: Push(‘(‘) +*( AB
C Operand: add C to P +*( ABC
* Operator: Top of the stack is ‘(‘ , Push(‘*’) +*(* ABC
D Operand: add D to P +*(* ABCD
- Operator: isp(‘*’) > icp(‘-‘), Pop(), Push (‘-’) +*(- ABCD*
E Operand: Add E to P +*(- ABCD*E
/ Operator: isp(‘-’) < icp(‘/‘), Push (‘/’) +*(-/ ABCD*E
F Operand: Add F to P +*(-/ ABCD*EF
) Right parenthesis: Pop operators from stack & pass to output till +* ABCD*EF/-
we get matching left parenthesis on top of the stack. Delete left
parenthesis from stack and discard right parenthesis.
/ Operator: isp(‘*’) = icp(‘/‘), Pop(), + ABCD*EF/-*
isp(‘+’) < icp(‘/’), Push (‘/’) +/
G Operand: Add G to P +/ ABCD*EF/-*G
- Operator: isp(‘/’) > icp(‘-‘), Pop() + ABCD*EF/-*G/
isp(‘+’) = icp(‘-‘), Pop() empty ABCD*EF/-*G/+
empty stack, Push(‘-‘) -
H Operand: Add H to P - ABCD*EF/-*G/+H
End of expression: pop all operators from stack & pass to output empty ABCD*EF/-*G/+H-

Evaluate a postfix expression

SIT,Nagpur
Notes On Algorithms and Data Structures

Let P is an arithmetic expression in postfix notation. In order to evaluate it stack is used to hold the operands.
Initially stack is empty and expression P is scanned from left to right.

Algorithm: to evaluate expression using postfix expression


While (not reached the end of P)
{
Read token;
If (token is operand)
Push it onto the stack;
If (token is operator)
{
Pop the stack and call the value A;
Pop the stack and call the value B;
Evaluate B op A using the operator just found;
Push the resulting value onto the stack;
}
}
Pop the stack (this is the final value)

Notes: At the end, there should be only one element left on the stack.
Let us use algorithm to evaluate postfix expression ABC+*D/ with A=3, B=4, C=5, D=9.

Token Action Stack


empty
A=3 Operand: Push(3) 3
B=4 Operand: Push(4) 3,4
C=5 Operand: Push(5) 3,4,5
+ Operator: Pop(), Pop(), 3
Calculate: 5+4=9, Push(9) 3,9
* Operator: Pop(), Pop(), empty
Calculate: 3 *9=27, Push(27) 27
D=9 Operand: Push(9) 27,9
/ Operator: Pop(), Pop(), empty
Calculate: 27/9=3, Push(3) 3
End of expression: Pop result from stack empty

In order to evaluate expression in single scan trick is use two stacks instead of one, one for operands and one for
operators.
We will use two stacks:
 Operand stack: to keep values (numbers) and
 Operator stack: to keep operators (+, -, *, . and ^).

In the following, “process” means, (i) pop operand stack once (value1) (ii) pop operator stack once (operator) (iii)
pop operand stack again (value2) (iv) compute value1 operator value2 (v) push the value obtained in operand
stack.

Algorithm:
Until the end of the expression is reached, get one character and perform only one of the steps (a) through (f):
(a) If the character is an operand, push it onto the operand stack.
(b) If the character is an operator, and the operator stack is empty then push it onto the operator stack.

SIT,Nagpur
Notes On Algorithms and Data Structures

(c) If the character is an operator and the operator stack is not empty, and the character's precedence is
greater than the precedence of the stack top of operator stack, then push the character onto the operator
stack.
(d) If the character is "(", then push it onto operator stack.
(e) If the character is ")", then "process" as explained above until the corresponding "(" is encountered in
operator stack. At this stage POP the operator stack and ignore "(."
(f) If cases (a), (b), (c), (d) and (e) do not apply, then process as explained above.

When there are no more input characters, keep processing until the operator stack becomes empty. The values
left in the operand stack is the final result of the expression.

Example: Expression 2+3*4


Token Decision and action Operand Operator Process
Stack Stack
2 Operand, push 2 in operand stack 2
+ Operator, stack is empty push + in operator stack 2 +
3 Operand, push 3 in operand stack. 2,3 +
* Operator: isp(‘+’) < icp(‘*‘), push * in operator stack 2,3 +.*
4 Operand, push 4 in operand stack 2,3,4 +.*
End of expression: pop two operands from operand stack and pop * from 2, 12 + 4*3
operator stack and perform operation. Push result in operand stack.
End of expression: pop two operands from operand stack and pop * from 14 12+2
operator stack and perform operation. Push result in operand stack.

Example: Expression 2*3+4


Token Decision and action Operand Operator Process
Stack Stack
2 Operand, push 2 in operand stack 2
* Operator, stack is empty push + in operator stack 2 *
3 Operand, push 3 in operand stack. 2,3 *
+ Operator: isp(‘*’) > icp(‘+‘), pop * from operator stack. Pop two operands 6 + 2*3
from operand stack. Perform operation, push result to operand stack. Also
push + to operator stack.
4 Operand, push 4 in operand stack 6,4 +
End of expression: pop two operands from operand stack and pop + from 10 6+4
operator stack and perform operation. Push result in operand stack.

Exercise:
1. Design and code a program to identify palindromes.
2. Design and code a program that prompts its user for an infix expression reads the expression, converts the
expression to postfix, evaluates the postfix expression, and displays the result. Your program should handle
only nonnegative single-digit integer operands and the integer operators +, -, *, /, %, and ^. Be sure not to
divide by zero
3. Convert following infix expressions to postfix and prefix expression
 A+B*C+(D*E+F)*G
 A+B*C-D/E
 A ** B ** C
 -A + B - C + D
 A ** -B + C
 (A + B) * D + E/(F + A * D) + C
SIT,Nagpur

You might also like