Unit-2: Linear Data Structure Stack
Unit-2: Linear Data Structure Stack
GTU # 3130702
Unit-2
Linear Data Structure
Stack
Deletion
Insertion
C
B … …
A
TOP
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 2
Stack Cont…
A pointer TOP keeps track of the top element in the stack.
Initially, when the stack is empty, TOP has a value of “zero”.
Each time a new element is inserted in the stack, the pointer is incremented by “one” before,
the element is placed on the stack.
The pointer is decremented by “one” each time a deletion is made from the stack.
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 3
Applications of Stack
Recursion
Keeping track of function calls
Evaluation of expressions
Reversing characters
Servicing hardware interrupts
Solving combinatorial problems using backtracking
Expression Conversion (Infix to Postfix, Infix to Prefix)
Game Playing (Chess)
Microsoft Word (Undo / Redo)
Compiler – Parsing syntax & expression
Finding paths
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 4
Procedure : PUSH (S, TOP, X)
This procedure inserts an element X to the top of a stack.
Stack is represented by a vector S containing N elements.
A pointer TOP represents the top element in the stack.
1. [Check for stack overflow] Stack is empty, TOP = 0, N=3 TOP = 3 -5
If TOP ≥ N TOP = 2 8
Then write (‘STACK OVERFLOW’) PUSH(S, TOP, 10) TOP = 1 10
Return S
2. [Increment TOP] PUSH(S, TOP, 8)
TOP ← TOP + 1
PUSH(S, TOP, -5)
3. [Insert Element]
S[TOP] ← X
PUSH(S, TOP, 6)
4. [Finished]
Return Overflow
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 5
Function : POP (S, TOP)
This function removes & returns the top element from a stack.
Stack is represented by a vector S containing N elements.
A pointer TOP represents the top element in the stack.
1. [Check for stack underflow] POP(S, TOP) TOP = 3 -5
TOP = 2 8
If TOP = 0
TOP = 1 10
Then write (‘STACK UNDERFLOW’) POP(S, TOP)
TOP = 0 S
Return (0)
2. [Decrement TOP] POP(S, TOP)
TOP ← TOP - 1
3. [Return former top element of POP(S, TOP)
stack]
Return(S[TOP + 1])
Underflow
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 6
Function : PEEP (S, TOP, I)
This function returns the value of the Ith element from the TOP of the stack. The element is not
deleted by this function.
Stack is represented by a vector S containing N elements.
1. [Check for stack underflow] PEEP (S, TOP, 2) TOP = 3 -5
8
If TOP-I+1 ≤ 0
10
Then write (‘STACK UNDERFLOW’) PEEP (S, TOP, 3)
S
Return (0)
2. [Return Ith element from top PEEP (S, TOP, 4)
of the stack]
Return(S[TOP–I+1]) Underflow
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 7
PROCEDURE : CHANGE (S, TOP, X, I)
This procedure changes the value of the Ith element from the top of the stack to X.
Stack is represented by a vector S containing N elements.
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 8
Algorithm: RECOGNIZE
Write an algorithm which will check that the given string belongs to following grammar or not.
L= {wcwR | w Є {a,b}*} (Where wR is the reverse of w)
• Given an input string named STRING on the alphabet {a, b, c} which contains a blank in its rightmost
character position.
• Function NEXTCHAR returns the next symbol in STRING.
• This algorithm determines whether the contents of STRING belong to the above language.
• The vector S represents the stack and TOP is a pointer to the top element of the stack.
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 9
Algorithm: RECOGNIZE
1. [Initialize stack by placing a 3. [Scan characters following ‘c’;
letter ‘c’ on the top] Compare them to the characters on
TOP 1 stack]
S [TOP] ← ‘c’ Repeat While S [TOP] ≠ ‘c’
NEXT ← NEXTCHAR (STRING)
2. [Get and PUSH symbols until either
X ← POP (S, TOP)
‘c’ or blank is encountered]
If NEXT ≠ X
NEXT ← NEXTCHAR (STRING)
Then Write(‘INVALID STRING’)
Repeat while NEXT ≠ ‘c’
Exit
If NEXT = ‘ ‘
Then Write (‘Invalid String’) 4. [Next symbol must be blank]
Exit NEXT ← NEXTCHAR (STRING)
Else Call PUSH (S, TOP, NEXT) If NEXT = ‘ ‘
NEXT ← NEXTCHAR (STRING) Then Write (‘VALID STRING’)
Else Write (‘INVALID STRING’)
5. [Finished]
Exit
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 10
Algorithm: RECOGNIZE
1. [Initialize stack by placing Input String: a b c b a □
a letter ‘c’ on the top]
TOP 1 NEXT
S [TOP] ← ‘c’ Character Stack
2. [Get and PUSH symbols until Scanned Content
either c’ or blank is 1 c
encountered]
a ca
NEXT ← NEXTCHAR (STRING)
Repeat while NEXT ≠ ‘c’ 2 b cab
If NEXT = ‘ ‘ c cab
Then Write (‘Invalid String’)
Exit
Else Call PUSH (S, TOP, NEXT)
NEXT ← NEXTCHAR (STRING)
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 11
Algorithm: RECOGNIZE
Input String: a b c b a □
3. Scan characters following ‘c’;
Compare them to the characters on stack NEXT
Repeat While S[TOP] ≠ ‘c’
NEXT ← NEXTCHAR (STRING) Character Stack
X ← POP (S, TOP) Scanned Content
If NEXT ≠ X 1 c
Then Write(‘Invalid String’)
a ca
Exit
2 b cab
4. [Next symbol must be blank] c cab
NEXT ← NEXTCHAR (STRING)
If NEXT = ‘ ‘ b ca
3
Then Write (‘VALID STRING’) a c
Else Write (‘INVALID STRING’) □
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 12
Algorithm : RECOGNIZE
Write an algorithm to determine if an input character string is of the form aibi where i>=1
i.e. number of a should be equal to no of b
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 13
Polish Expression & their Compilation
Evaluating Infix Expression
a+b*c+d*e
1 2
3
4
A repeated scanning from left to right is needed as operators appears inside the operands.
Repeated scanning is avoided if the infix expression is first converted to an equivalent
parenthesis free prefix or suffix (postfix) expression.
Prefix Expression: Operator, Operand, Operand
Postfix Expression: Operand, Operand, Operator
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 14
Polish Notation
This type of notation is known Lukasiewicz Notation or Polish Notation or Reverse Polish
Notation due to Polish logician Jan Lukasiewicz.
In both prefix and postfix equivalents of an infix expression, the variables are in same relative
position.
The expressions in postfix or prefix form are parenthesis free and operators are rearranged
according to rules of precedence for operators.
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 15
Polish Notation
Sr. Infix Postfix Prefix
1 a a a
2 a+b ab+ +ab
3 a+b+c ab+c+ ++abc
4 abc++ +a+bc
a + (b + c)
abc*+ +a * b c
5 a + (b * c)
abc+* *a+bc
6 a * (b + c)
a b *c* ** a b c
7 a*b*c
a+b+c a+b+c (ab+)+ c (ab+) c + ab+c+
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 16
Finding Rank of any Expression
E = ( A + B * C / D - E + F / G / ( H + I ))
Note: R = Rank, Rank of Variable = 1, Rank of binary operators = -1
Rank (E) = R(A) + R(+) + R(B) + R(*) + R(C) + R (/) + R(D) + R(-) + R(E) + R(+) + R(F) + R(/) + R(G)
+ R(/) + R(H) + R(+) + R(I)
Rank (E) = 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1 + (-1) + 1
Rank (E) = 1
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 17
Convert Infix to Postfix Expression
Symbol Input precedence Stack precedence Rank function (R)
function (F) function (G)
+, - 1 2 -1
*, / 3 4 -1
^ 6 5 -1
Variables 7 8 1
( 9 0 -
) 0 - -
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 18
Algorithm : REVPOL
Given an input string INFIX containing an infix expression which has been padded on the right
with ‘)’.
This algorithm converts INFIX into reverse polish and places the result in the string POLISH.
All symbols have precedence value given by the table.
Stack is represented by a vector S, TOP denotes the top of the stack, algorithm PUSH and POP
are used for stack manipulation.
Function NEXTCHAR returns the next symbol in given input string.
The integer variable RANK contains the rank of expression.
The string variable TEMP is used for temporary storage purpose.
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 19
1. [Initialize Stack] 5. [Remove symbols with greater precedence
TOP 1 from stack]
S[TOP] ← ‘(’ IF TOP < 1
Then write (‘INVALID’)
2. [Initialize output string and rank count]
EXIT
POLISH ‘’
Repeat while G(S[TOP]) > F(NEXT)
RANK 0
TEMP POP (S, TOP)
3. [Get first input symbol] POLISH POLISH O TEMP
NEXT NEXTCHAR(INFIX) RANK RANK + R(TEMP)
4. [Translate the infix expression] IF RANK <1
Repeat thru step 7 Then write (‘INVALID’)
while NEXT != ‘ ‘ EXIT
6. [Are there matching parentheses]
Symbol IPF (F) SPF (G) RF (R) IF G(S[TOP]) != F(NEXT)
+, - 1 2 -1 Then call PUSH (S,TOP, NEXT)
Else POP (S,TOP)
*, / 3 4 -1
7. [Get next symbol]
^ 6 5 -1 NEXT NEXTCHAR(INFIX)
Variables 7 8 1 8. [Is the expression valid]
IF TOP != 0 OR RANK != 1
( 9 0 - Then write (‘INVALID‘)
) 0 - - Else write (‘VALID’)
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 20
Input Content of Reverse polish expression Rank
(a+b^c^d)*(e+f/d)) Symbol stack
( 0
NEXT (
1. [Initialize Stack]
TOP 1
S[TOP] ← ‘(’
2. [Initialize output string and rank count]
POLISH ‘’
RANK 0
3. [Get first input symbol]
NEXT NEXTCHAR(INFIX)
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 21
Input Content of Reverse polish Rank
(a+b^c^d)*(e+f/d)) Symbol stack expression
( 0
NEXT ( 0
((
4. [Translate the infix expression]
Repeat thru step 7 a ((a 0
while NEXT!= ‘ ‘ + ((+
(( a 1
5. [Remove symbols with greater precedence from b ((+b a 1
stack] ((+
((+^ ab 2
^
IF TOP < 1
c ((+^c ab 2
Then write (‘INVALID’)
EXIT ^ ((+^^
((+^ abc 3
Repeat while G(S[TOP]) > F(NEXT) d ((+^^d abc 3
TEMP POP (S, TOP)
POLISH POLISH O TEMP ) ((( abcd^^+ 1
RANK RANK + R(TEMP)
IF RANK <1
Then write (‘INVALID’)
EXIT
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 22
Perform following operations
Convert the following infix expression to postfix. Show the stack contents.
A$B-C*D+E$F/G
A+B–C*D*E$F$G
a+b*c-d/e*h
((a+b^c^d)*(e+f/d))
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 23
General Infix-to-Postfix Conversion
Create an empty stack called stack for keeping operators. Create an empty list for output.
Read the character list from left to right and perform following steps
1 If the character is an operand (Variable), append it to the end of the output list
2 If the character is a left parenthesis ‘(’, push it on the stack
3 If the character is a right parenthesis ‘)’, pop the stack until the corresponding left parenthesis ‘)’ is
removed. Append each operator to the end of the output list.
4 If the token is an operator, *, /, +, or -, push it on the stack. However, first remove any operators already on
the stack that have higher or equal precedence and append them to the output list.
(a+b^c^d)*(e+f/d)
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 24
Evaluation of postfix expression
Each operator in postfix string refers to the previous two operands in the string.
Each time we read an operand, we PUSH it onto Stack.
When we reach an operator, its operands will be top two elements on the stack.
We can then POP these two elements, perform the indicated operation on them and PUSH the
result on the stack so that it will available for use as an operand for the next operator.
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 25
Evaluation of postfix expression
Evaluate Expression: 5 6 2 - +
Empty Stack
Read – , is it operator? POP
Read 5, is it operand? PUSH two symbols and perform
Read 6, is it operand? PUSH 2 operation and PUSH result
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 26
Algorithm: EVALUATE_POSTFIX
Given an input string POSTFIX representing postfix expression.
This algorithm evaluates postfix expression and put the result into variable VALUE.
Stack is represented by a vector S, TOP denotes the top of the stack, Algorithm PUSH and POP
are used for stack manipulation.
Function NEXTCHAR returns the next symbol in given input string.
OPERAND1, OPERAND2 and TEMP are used for temporary variables
PERFORM_OPERATION is a function which performs required operation on OPERAND1 &
OPERAND2.
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 27
Algorithm: EVALUATE_POSTFIX
1. [Initialize Stack]
TOP 0
VALUE 0
2. [Evaluate the postfix expression]
Repeat until last character
TEMP NEXTCHAR (POSTFIX)
If TEMP is DIGIT
Then PUSH (S, TOP, TEMP)
Else OPERAND2 POP (S, TOP)
OPERAND1 POP (S, TOP)
VALUE PERFORM_OPERATION(OPERAND1, OPERAND2, TEMP)
PUSH (S, POP, VALUE)
3. [Return answer from stack]
Return (POP (S, TOP))
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 28
Evaluation of postfix expression
Evaluate Expression: 5 4 6 + * 4 9 3 / + *
Evaluate Expression: 7 5 2 + * 4 1 1 + / -
Evaluate Expression: 12, 7, 3, -, /, 2, 1, 5, +, *, +
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 29
Algorithm: EVALUATE_PREFIX
Given an input string PREFIX representing prefix expression.
This algorithm evaluates prefix expression and put the result into variable VALUE.
Stack is represented by a vector S, TOP denotes the top of the stack, Algorithm PUSH and POP
are used for stack manipulation.
Function NEXTCHAR returns the next symbol in given input string.
OPERAND1, OPERAND2 and TEMP are used for temporary variables
PERFORM_OPERATION is a function which performs required operation on OPERAND1 &
OPERAND2.
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 30
Algorithm: EVALUATE_PREFIX
1. [Initialize Stack]
TOP 0
VALUE 0
2. [Evaluate the prefix expression]
Repeat from last character up to first
TEMP NEXTCHAR (PREFIX)
If TEMP is DIGIT
Then PUSH (S, TOP, TEMP)
Else OPERAND1 POP (S, TOP)
OPERAND2 POP (S, TOP)
VALUE PERFORM_OPERATION(OPERAND1, OPERAND2, TEMP)
PUSH (S, POP, VALUE)
3. [Return answer from stack]
Return (POP (S, TOP))
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 31
Recursion
A procedure that contains a procedure call to itself or a procedure call to second procedure
which eventually causes the first procedure to be called is known as recursive procedure.
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 32
Algorithm to find factorial using recursion
Given integer number N
This algorithm computes factorial of N.
Stack S is used to store an activation record associated with each recursive call.
TOP is a pointer to the top element of stack S.
Each activation record contains the current value of N and the current return address
RET_ADDE.
TEMP_REC is also a record which contains two variables PARAM & ADDRESS.
Initially return address is set to the main calling address. PARAM is set to initial value N.
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 33
Algorithm: FACTORIAL
1. [Save N and return Address]
CALL PUSH (S, TOP, TEMP_REC)
2. [Is the base criterion found?]
If N=0
then FACTORIAL 1
GO TO Step 4
Else PARAM N-1
ADDRESS Step 3
GO TO Step 1
3. [Calculate N!]
FACTORIAL N * FACTORIAL
4. [Restore previous N and return address]
TEMP_REC POP(S,TOP)
(i.e. PARAM N, ADDRESS RET_ADDR)
GO TO ADDRESS
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 34
Trace of Algorithm FACTORIAL, N=2
Level Number Description Stack Content
Enter Level 1 Step 1: PUSH (S,0,(N=2, main address)) 2
(main call) Step 2: N!=0 Main
PARAM N-1 (1), ADDR Step 3 Address
TOP
Dr. Pradyumansinh U. Jadeja #3130702 (DS) Unit 2 – Linear Data Structure (Stack) 36
Data Structures (DS)
GTU # 3130702
Thank
You