Elementary Data Structure
Elementary Data Structure
2 3 5 2
4 5 6 7 7 6 4 3
Queue Stack
POP(S)
if STACK-EMPTY(S)
then error \underow"
else topS ] topS ] ; 1
return S topS ] + 1]
4 top
tail head
DEQUEUE(Q)
x = QheadQ]]
if headQ] = lengthQ]
then headQ] = 1
else headQ] = headQ] + 1
return x
A list-based implementation would eliminate the pos-
sibility of overow.
All are O(1) time operations.
Dynamic Set Operations
Perhaps the most important class of data structures
maintain a set of items, indexed by keys.
There are a variety of implementations of these dic-
tionary operations, each of which yield dierent time
bounds for various operations.
Search(S,k) { A query that, given a set S and a
key value k, returns a pointer x to an element in
S such that keyx] = k, or nil if no such element
belongs to S .
Insert(S,x) { A modifying operation that augments
the set S with the element x.
Delete(S,x) { Given a pointer x to an element in
the set S , remove x from S. Observe we are given
a pointer to an element x, not a key value.
Min(S), Max(S) { Returns the element of the to-
tally ordered set S which has the smallest (largest)
key.
Next(S,x), Previous(S,x) { Given an element x
whose key is from a totally ordered set S , returns
the next largest (smallest) element in S , or NIL if
x is the maximum (minimum) element.
Pointer Based Implementation
We can also maintain a directory in either a singly or
doubly linked list.
L
A B C D E F
L A B C D E F
INSERTION
LIST-INSERT(L, x)
nextx] = headL]
if headL] <> NIL
then prevheadL]] = x
headL] = x
prevx] = NIL
LIST-DELETE(L, x)
if prevx] <> NIL
then nextprevx]] = nextx]
else headL] = nextx]
if nextx] <> NIL
then prevnextx]] = prevx]
Sentinels
Boundary conditions can be eliminated using a sentinel
element which doesn't go away.
NIL
LIST-SEARCH'(L, k)
x = nextnilL]]
while x <> NILL] and keyx] <> k
do x = nextx]
return x
LIST-INSERT'(L, x)
nextx] = nextnilL]]
prevnextnilL]]] = x
nextnilL]] = x
prevx] = NILL]
LIST-DELETE'(L, x)
nextprevx]] <> nextx]
nextprevx]] = prevx]