Chapter 10 Elementary Data Structures
10.1 Stacks and queues
-
Stacks and queues are dynamic sets in which the element removed from the set by the DELETE operation is prespecified.
-
In a stack, the element deleted from the set is the one most recently inserted: the stack implements a last-in, first-out, or LIFO, policy.
-
In a queue, the element deleted is always the one that has been in the set for the longest time: the queue implements a first-in, first-out, or FIFO, policy.
Stacks
- The INSERT operation on a stack is often called PUSH, and the DELETE operation, which does not take an element argument, is often called POP.
-
push, which adds an element to the collection, and
-
pop, which removes the most recently added element that was not yet removed.
- We implement a stack of at most n elements with an array S[1…n].The array has an attribute S.top that indexes the most recently inserted element.The stack consists of elements S[1…S.top], where S[1] is the element at the bottom of the stack and S[S.top] is the element at the top.
-
When S.top = 0, the stack contains no elements and is empty.
-
If we attempt to pop an empty stack, we say the stack underflows, which is normally an error. If S.top exceeds n, the stack overflows.
-
We can implement each of the stack operations with just a few lines of code:
STACK-EMPTY(S)
1 if S.top == 0
2 return TURE
3 else return FALSE
PUSH(S,x)
1 S.top = S.top + 1
2 S[S.top] = x
POP(S)
1 if STACK-EMPTY(S)
2 error "underflow"
3 else S.top = s.top - 1
4 return S[S.top + 1]
Queues
-
We call the INSERT operation on a queue ENQUEUE, and we call the DELETE operation DEQUEUE;
-
The queue has a head and a tail.
-
We can implement each of the queues operations with just a few lines of code(omitted the error checking for underflow and overflow.):
ENQUEUES(Q,x)
1 Q[Q.tail] = x
2 if Q.tail == Q.length
3 Q.tail = 1
4 else Q.tail = Q.tail + 1
DEQUEUES(Q)
1 x = Q[Q.head]
2 if Q.head = = Q.length
3 Q.head = 1
4 else Q.head = Q.head + 1
5 return x