Ajaydpdata Structures and Algorithms JAVA
Ajaydpdata Structures and Algorithms JAVA
Ajaydpdata Structures and Algorithms JAVA
LINKED LISTS
• Stacks
• Queues
• Linked Lists
• Double-Ended Queues
Algorithm size():
return t +1
Algorithm isEmpty():
return (t<0)
Algorithm top():
if isEmpty() then
throw a StackEmptyException
return S[t]
...
Stacks, Queues, and Linked Lists 5
An Array-Based Stack (contd.)
• Pseudo-Code (contd.)
Algorithm push(o):
if size() = N then
throw a StackFullException
t←t+1
S[t] ← o
Algorithm pop():
if isEmpty() then
throw a StackEmptyException
e←S[t]
S[t]←null
t←t-1
return e
14 cool(i);
fool:
PC = 320
m=7 }
cool: cool(int j) {
PC = 216
int k=7;
j=5
k=7
216 fool(k);
main:
PC = 14
i=5 }
320 fool(int m) {
Java Stack
}
Java Program
Stacks, Queues, and Linked Lists 12
Queues
• A queue differs from a stack in that its insertion and
removal routines follows the first-in-first-out (FIFO)
principle.
• Elements may be inserted at any time, but only the
element which has been in the queue the longest
may be removed.
• Elements are inserted at the rear (enqueued) and
removed from the front (dequeued)
Front Rear
Queue
a0 a1 a2 ... an-1
Q ...
0 1 2 f r N−1
Q ...
0 1 2 r f N−1
Algorithm size():
return (N - f + r) mod N
Algorithm isEmpty():
return (f = r)
Algorithm front():
if isEmpty() then
throw a QueueEmptyException
return Q[f]
Algorithm dequeue():
if isEmpty() then
throw a QueueEmptyException
temp ← Q[f]
Q[f] ← null
f ← (f + 1) mod N
return temp
Algorithm enqueue(o):
if size = N - 1 then
throw a QueueFullException
Q[r] ← o
r ← (r +1) mod N
• the head of the list is the front of the queue, the tail
of the list is the rear of the queue
• why not the opposite?
head tail
∅ ∅
header trailer
last
header secondtolast trailer
header trailer
s1=1
s5=4
s3=2
s2=1 s4=1
p0 p1 p2 p3 p4 p5 p6
p0 p1 p2 p3 p4 p5 p6
Algorithm computeSpan2(P):
Input: An n-element array P of numbers
Output: An n-element array S of numbers such that
S[i] is the span of the stock on day i.
Let S be an array of n numbers and D an empty stack
for i=0 to n-1 do
done←false
while not(D.isEmpty() or done) do
if P[i]≥P[D.top()] then
D.pop()
else
done←true
if D.isEmpty() then
h← -1
else
h←D.top()
S[i]←i-h
D.push(i)
return array S
• Let’s analysize computeSpan2’s run time...