You are on page 1of 6

The Stack ADT (§4.2.

1)
Elementary Data The Stack ADT stores
arbitrary objects
Structures Insertions and deletions Auxiliary stack
follow the last-in first-out operations:
scheme „ top(): returns the last
Stacks, Queues, & Lists inserted element without
Think of a spring-loaded removing it
Amortized analysis plate dispenser „ size(): returns the
number of elements
Trees Main stack operations:
stored
„ push(Object o): inserts
element o „ isEmpty(): a Boolean
value indicating whether
„ pop(): removes and returns
no elements are stored
the last inserted element
Elementary Data Structures 2

Array-based Stack (§4.2.2)


Applications of Stacks Algorithm pop():
if isEmpty() then
A simple way of throw EmptyStackException
Direct applications implementing the else
„ Page-visited history in a Web browser Stack ADT uses an t←t−1
array
„ Undo sequence in a text editor return S[t + 1]
We add elements
„ Chain of method calls in the Java Virtual from left to right Algorithm push(o)
Machine or C++ runtime environment A variable t keeps if t = S.length − 1 then
track of the index of throw FullStackException
Indirect applications the top element else
„ Auxiliary data structure for algorithms (size is t+1) t←t+1
„ Component of other data structures S[t] ← o

S
0 1 2 t
Elementary Data Structures 3 Elementary Data Structures 4

Growable Array-based Comparison of the


Stack Strategies
In a push operation, when
the array is full, instead of We compare the incremental strategy and
throwing an exception, we Algorithm push(o) the doubling strategy by analyzing the total
can replace the array with if t = S.length − 1 then
A ← new array of time T(n) needed to perform a series of n
a larger one
size … push operations
How large should the new for i ← 0 to t do
array be? We assume that we start with an empty
A[i] ← S[i]
incremental strategy: stack represented by an array of size 1
„
S←A
increase the size by a t←t+1 We call amortized time of a push operation
constant c
S[t] ← o the average time taken by a push over the
„ doubling strategy: double
the size series of operations, i.e., T(n)/n
Elementary Data Structures 5 Elementary Data Structures 6

1
Analysis of the Direct Analysis of the
Incremental Strategy Doubling Strategy
We replace the array k = log2 n
We replace the array k = n/c times times
The total time T(n) of a series of n push The total time T(n) of a series
geometric series
operations is proportional to of n push operations is 2
n + c + 2c + 3c + 4c + … + kc = proportional to 4
n + c(1 + 2 + 3 + … + k) = n + 1 + 2 + 4 + 8 + …+ 2k = 1 1
n + ck(k + 1)/2 n + 2k + 1 −1 = 2n −1
Since c is a constant, T(n) is O(n + k2), i.e., 8
T(n) is O(n)
O(n2) The amortized time of a push
The amortized time of a push operation is O(n) operation is O(1)
Elementary Data Structures 7 Elementary Data Structures 8

Accounting Method Analysis Amortization Scheme for


of the Doubling Strategy the Doubling Strategy
Consider again the k phases, where each phase consisting of twice
The accounting method determines the amortized as many pushes as the one before.
running time with a system of credits and debits
At the end of a phase we must have saved enough to pay for the
We view a computer as a coin-operated device requiring array-growing push of the next phase.
1 cyber-dollar for a constant amount of computing. At the end of phase i we want to have saved i cyber-dollars, to pay
for the array growth for the beginning of the next phase.
„ We set up a scheme for charging operations. This $ $ $ $

is known as an amortization scheme.


$
$ $ $ $
$

„ The scheme must give us always enough money to


0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
pay for the actual cost of the operation.
„ The total cost of the series of operations is no more • We charge $3 for a push. The $2 saved for a regular push are
than the total amount charged. “stored” in the second half of the array. Thus, we will have
2(i/2)=i cyber-dollars saved at then end of phase i.
(amortized time) ≤ (total $ charged) / (# operations) • Therefore, each push runs in O(1) amortized time; n pushes run
in O(n) time.
Elementary Data Structures 9 Elementary Data Structures 10

The Queue ADT (§4.3.1) Applications of Queues


The Queue ADT stores Auxiliary queue operations:
arbitrary objects „ front(): returns the element
at the front without removing
Direct applications
Insertions and deletions follow
the first-in first-out scheme it „ Waiting lines
Insertions are at the rear of „ size(): returns the number of
the queue and removals are elements stored „ Access to shared resources (e.g., printer)
isEmpty(): returns a Boolean
at the front of the queue „
value indicating whether no
„ Multiprogramming
Main queue operations: elements are stored
enqueue(object o): inserts Indirect applications
„
element o at the end of the
Exceptions
queue „ Attempting the execution of „ Auxiliary data structure for algorithms
dequeue or front on an
„ dequeue(): removes and
empty queue throws an „ Component of other data structures
returns the element at the
front of the queue EmptyQueueException

Elementary Data Structures 11 Elementary Data Structures 12

2
Singly Linked List Queue with a Singly Linked List
A singly linked list is a We can implement a queue with a singly linked list
concrete data structure next „ The front element is stored at the first node
consisting of a sequence „ The rear element is stored at the last node
of nodes
The space used is O(n) and each operation of the
Each node stores
node Queue ADT takes O(1) time r
„ element elem
„ link to the next node nodes

f ∅

A B C D
elements
Elementary Data Structures 13 Elementary Data Structures 14

List ADT (§5.2.2) Doubly Linked List


A doubly linked list provides a natural prev next
implementation of the List ADT
The List ADT models a Accessor methods:
Nodes implement Position and store:
sequence of positions „ first(), last() „ element
storing arbitrary objects „ before(p), after(p) link to the previous node
„ elem node
It allows for insertion Update methods: „ link to the next node
and removal in the „ replaceElement(p, o), Special trailer and header nodes
“middle” swapElements(p, q)
trailer
header nodes/positions
Query methods: „ insertBefore(p, o),
insertAfter(p, o),
„ isFirst(p), isLast(p)
„ insertFirst(o),
insertLast(o)
„ remove(p)
elements
Elementary Data Structures 15 Elementary Data Structures 16

Trees (§6.1) Tree ADT (§6.1.2)


We use positions to abstract Query methods:
In computer science, a
nodes boolean isInternal(p)
tree is an abstract model Computers”R”Us „

of a hierarchical Generic methods: „ boolean isExternal(p)


structure „ integer size() „ boolean isRoot(p)
A tree consists of nodes Sales Manufacturing R&D „ boolean isEmpty() Update methods:
with a parent-child „ objectIterator elements() „ swapElements(p, q)
relation „ positionIterator positions() „ object replaceElement(p, o)
US International Laptops Desktops Accessor methods:
Applications: Additional update methods
„ Organization charts „ position root() may be defined by data
„ File systems „ position parent(p) structures implementing the
Europe Asia Canada
„ Programming „ positionIterator children(p) Tree ADT
environments

Elementary Data Structures 17 Elementary Data Structures 18

3
Preorder Traversal (§6.2.3) Postorder Traversal (§6.2.4)
A traversal visits the nodes of a Algorithm preOrder(v) In a postorder traversal, a Algorithm postOrder(v)
tree in a systematic manner node is visited after its
visit(v) descendants for each child w of v
In a preorder traversal, a node is
visited before its descendants for each child w of v Application: compute space postOrder (w)
Application: print a structured preorder (w) used by files in a directory and visit(v)
document its subdirectories
9
1 cs16/
Make Money Fast!
8
3 7
2 5 9 todo.txt
homeworks/ programs/
1. Motivations 2. Methods References 1K

6 7 8 1 2 4 5 6
3 4
2.1 Stock 2.2 Ponzi 2.3 Bank h1c.doc h1nc.doc DDR.java Stocks.java Robot.java
1.1 Greed 1.2 Avidity
Fraud Scheme Robbery 3K 2K 10K 25K 20K

Elementary Data Structures 19 Elementary Data Structures 20

Amortized Analysis of
Tree Traversal Binary Trees (§6.3)
A binary tree is a tree with the Applications:
Time taken in preorder or postorder traversal following properties: „ arithmetic expressions
of an n-node tree is proportional to the sum, „ Each internal node has two „ decision processes
children
taken over each node v in the tree, of the „ The children of a node are an
„ searching

time needed for the recursive call for v. ordered pair A


We call the children of an internal
„ The call for v costs $(cv + 1), where cv is the node left child and right child
number of children of v Alternative recursive definition: a B C
binary tree is either
„ For the call for v, charge one cyber-dollar to v and
„ a tree consisting of a single node,
charge one cyber-dollar to each child of v. or D E F G
„ Each node (except the root) gets charged twice: „ a tree whose root has an ordered
pair of children, each of which is a
once for its own call and once for its parent’s call. binary tree
H I
„ Therefore, traversal time is O(n).
Elementary Data Structures 21 Elementary Data Structures 22

Arithmetic Expression Tree Decision Tree


Binary tree associated with an arithmetic expression Binary tree associated with a decision process
„ internal nodes: operators „ internal nodes: questions with yes/no answer
„ external nodes: operands „ external nodes: decisions
Example: arithmetic expression tree for the Example: dining decision
expression (2 × (a − 1) + (3 × b))

+ Want a fast meal?


Yes No
× ×
How about coffee? On expense account?
2 − 3 b
Yes No Yes No
a 1 Starbucks In ‘N Out Antoine's Denny’s

Elementary Data Structures 23 Elementary Data Structures 24

4
Properties of Binary Trees Inorder Traversal
In an inorder traversal a Algorithm inOrder(v)
Notation Properties: node is visited after its left
n number of nodes „ e = i + 1 subtree and before its right if isInternal (v)
e number of subtree inOrder (leftChild (v))
„ n = 2e − 1
external nodes Application: draw a binary visit(v)
„ h ≤ i tree
i number of internal if isInternal (v)
x(v) = inorder rank of v
nodes „ h ≤ (n − 1)/2
„

„ y(v) = depth of v
6 inOrder (rightChild (v))
h height „ e ≤ 2h

„ h ≥ log2 e
2 8

„ h ≥ log2 (n + 1) − 1 1 4 7 9

3 5

Elementary Data Structures 25 Elementary Data Structures 26

Euler Tour Traversal Printing Arithmetic Expressions


Generic traversal of a binary tree Specialization of an inorder Algorithm printExpression(v)
Includes a special cases the preorder, postorder and inorder traversals traversal
print operand or operator
if isInternal (v)
Walk around the tree and visit each node three times: „
when visiting node print(“(’’)
„ on the left (preorder)
print “(” before traversing left
„ from below (inorder)
„
subtree
inOrder (leftChild (v))
„ on the right (postorder)
„ print “)” after traversing right print(v.element ())
subtree
+ if isInternal (v)
+ inOrder (rightChild (v))
L × R ×
B × × print (“)’’)
2 − 3 2
2 − 3 b
5 1 ((2 × (a − 1)) + (3 × b))
a 1
Elementary Data Structures 27 Elementary Data Structures 28

Linked Data Structure for Linked Data Structure for


Representing Trees (§6.4.3) Binary Trees (§6.4.2)
A node is represented by A node is represented
an object storing ∅ by an object storing ∅
„ Element „ Element
„ Parent node Parent node
Sequence of children B „

B
„
nodes „ Left child node
Right child node
Node objects implement ∅ ∅ „

the Position ADT Node objects implement ∅ ∅


the Position ADT
A D F
B B A D

A D F A D ∅ ∅ ∅ ∅

C E ∅ ∅
C E C E
C E
Elementary Data Structures 29 Elementary Data Structures 30

5
Array-Based Representation of
Binary Trees (§6.4.1)
nodes are stored in an array
1
A

2 3
B D

„ let rank(node) be defined as follows:


„ rank(root) = 1 4 5 6 7
E F C J
„ if node is the left child of parent(node),
rank(node) = 2*rank(parent(node))
„ if node is the right child of parent(node),
10 11
rank(node) = 2*rank(parent(node))+1
G H
Elementary Data Structures 31

You might also like