Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
ALGORITHMS
Last week :
Doubly Linked List
Introduction to Stacks
PUSH, POP
Minimizing Overflow
Linked representation of Stacks
PUSH, POP
This week:
Arithmetic Expressions; Polish Notation
TOP = 3
MAXSTK= 8
Example 6.2
Simulate PUSH(STACK,WWW)
1.Since TOP=3, control goto step 2
2.TOP=3+1= 4
STCK[TOP]=STACK[4]=WWW
4.Return
(b) Simulate POP(STACK,ITEM)
1.Since TOP=3, control goto step 2
2.ITEM=ZZZ
3.TOP=3-1=2
4.Return
Minimizing overflow
Linked representation of Stacks
Linked stack is implemented using singly linked list
INFO fields of nodes hold elements of stack
Link field contains neighboring element
START act as TOP
NULL pointer of last node act as bottom of stack
Procedure 6.3: Push link Stack
PUSH_LINKSTACK(INFO, LINK, TOP,AVAIL,ITEM)
1.If avail=NULL, then write OVERFLOW & Exit
2. Set New=avail & avail=Link[avail]
3. Set Info[New]= Item
4. Set link[new]=Top
5. Set Top=New
6. Exit
Procedure 6.4: Pop linkStack
POP_LINKSTACK(INFO, LINK, TOP,AVAIL,ITEM)
1.If Top=NULL, then write UNDERFLOW & Exit
2. Set Item=Info[Top]
3.Set Temp=Top & Top=Link[Top]
4. Set link[Temp]=avail & avail=Temp
5. Exit
Example 6.4
1.Push BBB
2.Pop
3.Pop
4.Push MMM
Arithmetic Notation
Highest: Exponentiation
Next Highest : Multiplication (*) & Division (/)
Lowest: Addition (+) & Subtraction (-)
(a) (A – B ) * ( D / E) = ?
(b) (A+ B D ) / ( E – F ) + G =?
(c) A * ( B + D) / E – F * ( G + H/K) = ?
Infix to prefix
Solved Problem 6.11
(a) (A – B ) * ( D / E) = ?
(b) (A+ B D ) / ( E – F ) + G =?
Quick Sort, An Application of Stacks
22 33 11 40 77 90 44 60 99 55 88 66
22 33 11 40 44 90 77 60 99 55 88 66
Now 44 is on its Correct Position
We can Process only One Sub-List at a Time
Two Stacks Lower and Upper will be used
Boundary Values :
Address of the First and Last values of Sub-List
Lower 1 Upper 12
Lower Empty Upper Empty
Lower 1,6 Upper 4,12
Lower 1,6 Upper 4,10
A[6] A[7] A[8] A[9] A[10] A[11] A[12]
90 77 60 99 55 88 66
66 77 60 99 55 88 90
66 77 60 90 55 88 99
66 77 60 88 55 90 99
First Sub-List Second Sub-List
QUICK ( A, N, BEG, END, LOC )
A : Name of Array
N : Number of Elements
BEG : Beginning Boundary Value
END : Ending Boundary Value
LOC : Position of the First Element
Local Variables :
LEFT
RIGHT
Procedure 6,7 Quick (A, N, BEG, END, LOC)
1. [Initialize] TOP := 0
2. [PUSH Boundary values of A onto Stacks when 2 or More Elements]
If N > 1, then TOP:=TOP+1, LOWER[1]:=1, UPPER[1]:=N
3. Repeat Steps 4 to 7 while TOP != 0
4. [Pop Sub-List from Stacks]
Set BEG := LOWER[TOP] , END := UPPER[TOP]
TOP := TOP -1
5. Call QUICK (A, N, BEG, END, LOC)
6. [Push Left Sub-List onto Stacks when 2 or More Elements]
If BEG < LOC - 1 then TOP := TOP + 1, LOWER[TOP] := BEG,
UPPER[TOP] := LOC – 1 [End of If Structure]
41