You are on page 1of 6

The Stack ADT (§2.1.

1)
Elementary Data Š The Stack ADT stores
arbitrary objects
Structures Š Insertions and deletions Š Auxiliary stack
follow the last-in first-out operations:
scheme „ object top(): returns the
Stacks, Queues, & Lists Š Think of a spring-loaded last inserted element
plate dispenser without removing it
Amortized analysis integer size(): returns the
Š Main stack operations: „

number of elements
Trees „ push(object): inserts an
stored
element
„ object pop(): removes and „ boolean isEmpty():
returns the last inserted indicates whether no
element elements are stored

Elementary Data Structures 2

Array-based Stack (§2.1.1)


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 (§1.5) 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
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 (§2.1.2) Applications of Queues


Š The Queue ADT stores arbitrary Š Auxiliary queue
objects operations: Š Direct applications
Š Insertions and deletions follow „ object front(): returns the
the first-in first-out scheme element at the front without „ Waiting lines
Š Insertions are at the rear of the removing it
queue and removals are at the „ integer size(): returns the „ Access to shared resources (e.g., printer)
number of elements stored
front of the queue „ Multiprogramming
„ boolean isEmpty(): indicates
Š Main queue operations:
„ enqueue(object): inserts an
whether no elements are
stored
Š Indirect applications
element at the end of the
queue Š Exceptions „ Auxiliary data structure for algorithms
Attempting the execution of
„ object dequeue(): removes and „
dequeue or front on an
„ Component of other data structures
returns the element at the front
of the queue empty queue throws an
EmptyQueueException
Elementary Data Structures 11 Elementary Data Structures 12
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 (§2.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 (§2.3) Tree ADT (§2.3.1)


Š 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


Preorder Traversal (§2.3.2) Postorder Traversal (§2.3.2)
Š 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 (§2.3.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


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 Š Application: draw a binary
external nodes visit(v)
i number of internal „ h≤i tree
x(v) = inorder rank of v if isInternal (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: „
print(“(’’)
when visiting node
„ 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 (§2.3.4) Binary Trees
Š 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
Array-Based Representation of
Binary Trees
Š 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