Stacks and Queues Dr. Andrew Wallace PhD BEng(hons) EurIng
Overview In and out Stack operations Stack implementation Queue operations Queue implementation Complexity
In and Out Data Memory Address Data Memory Address Data Memory Address Data Memory Address Data Memory Address Data Memory Address Data Memory Address Data Memory Address Stack Queue
In and out LIFO Last in first out FIFO First in first out
Stack Operations S[1 … S.top] Is empty Push Pop
Stack Operations IsEmpty(S) if S.top == null return TRUE else return FALSE
Stack Operations Push(s.x) S.top = S.top + 1 S[S.top] = s.x data S.top s.x
Stack Operations Pop(S) ASSERT(!IsEmpty(S)) S.top = S.top -1 return S[S.top + 1] data S.top s.x
Stack Implementation Array Linked list
Stack Implementation s.tops.top s.tops.top
Queue Operations Q[Q.head … Q.tail] Enqueue(Q.tail) Dequeue(Q.head)
Queue Operations Enqueue(Q.x) Q.tail = Q.x if Q.tail == Q.length Q.tail = 1 else Q.tail = Q.tail + 1 data Q.head Q.tail Q.x Q.tail
Queue Operations Dequeue(Q) Q.x = Q[Q.head] if Q.head == Q.length Q.head = 1 else Q.head = Q.head + 1 return Q.x data Q.tail data Q.head Q.x
Queue Implementation Array Linked list
Queue Implementation Q.headQ.head Q.TailQ.Tail Q.TailQ.Tail
Queue Implementation Q.headQ.head 90 Q.TailQ.Tail Q.TailQ.Tail
Complexity Pop(S) ASSERT(!IsEmpty(S)) S.top = S.top -1 return S[S.top + 1] Dequeue(Q) Q.x = Q[Q.head] if Q.head == Q.length Q.head = 1 else Q.head = Q.head + 1 return Q.x Q(1)
Questions?