0% found this document useful (0 votes)
10 views15 pages

Line Ards

Uploaded by

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

Line Ards

Uploaded by

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

Linear Data Structures

LIFO – Polish notation


Context Saving
Arithmetic Expression
Infix: 1+2x3+1/2 = ?
(1+(2x3)+1)/2
(1+(2x3))+(1/2)
((1+2)x(3+1))/2
==4=7.5
6

Postfix (Polish notation):


Let A, B, be operands, ♦ an operator.
Instead of A♦B, write AB♦
Arithmetic Expression (2)
Example:
Infix: Infix:
((1+2)x(3+1))/2 (1+(2x3))+(1/2)
Postfix: Postfix:
((1+2)x(3+1))2/ (1+(2x3))(1/2)+
(1+2)(3+1)x2/ (1+(2x3))12/+
(1+2)31+x2/ 1(2x3)+12/+
12+31+x2/ 123x+12/+
Arithmetic Expression (3)
Advantage of Polish Notation:
No ambiguity!

A-B-C =? (A-B)-C A-(B-C)

AB-C- ABC--
Arithmetic Expression (4)
But how do we read it?
Can the Polish people really understand this?
12+31+x2/
Arithmetic Expression (5)
Algorithm for Computing Postfix
Arithmetic Expression:
Data Structures: A[1..n] - a legal arithmetic
expression in postfix notation.
E - a stack of
evaluated parts of the expression.

Output: Top of stack.


Arithmetic Expression (6)
The Algorithm
For i=1 to n do
If A[i] is not an operator
then PUSH(E,A[i])
else POP(E,X)
POP(E,Y)
PUSH(E,Y A[i] X) (remember:A[i] is
operator)

endFor
POP(E,Solution)
Arithmetic Expression (7)
Example: 12+31+x2/ ((1+2)x(3+1))/2=6

operator

1 + 2 3=

2
1
3
Arithmetic Expression (7)
Example: 12+31+x2/ ((1+2)x(3+1))/2=6

operator

3 + 1 4=
1
3
4
3
Arithmetic Expression (7)
Example: 12+31+x2/ ((1+2)x(3+1))/2=6

operator

3 x 4 12=

4
2
12
3
Arithmetic Expression (7)
Example: 12+31+x2/ ((1+2)x(3+1))/2=6

6
operator

12 / 2 6=

2
12
6
Arithmetic Expression (8)

Exercise:

Use LIFO to write a simple algorithm


that recognizes whether an input
array is a legal arithmetic
expression in postfix notation.
Context Saving

Telephone switches

Then…

Now: digital. Huge programs, thousands


of lines of code. No loops, no functions.
Context Saving (2)
Software:
Variable I
Loops:

A B C
Subroutines: CALL B CALL C CALL A
Context Saving (3)
Software:
Recursive Subroutines:
A

CALL A

Example: Sudoku.
Context saving: LIFO.

You might also like