Stack Algorithms: Push and Pop
// stack has indexes 0 to maxSize - 1; top = -1 when the stack is empty
procedure push(item):
if top == maxSize - 1 then
print("Stack is full")
else
top = top + 1
stack[top] = item
end if
end procedure
function pop():
if top == -1 then
print("Stack is empty")
return null
else
item = stack[top]
top = top - 1
return item
end if
end function
Queue Algorithms: Enqueue and Dequeue
// queue has indexes 0 to maxSize - 1; front = 0 and rear = -1 when the queue is empty
procedure enqueue(item):
if rear == maxSize - 1 then
print("Queue is full")
else
rear = rear + 1
queue[rear] = item
end if
end procedure
function dequeue():
if front > rear then
print("Queue is empty")
return null
else
item = queue[front]
front = front + 1
return item
end if
end function
| Operation | Stack (bottom to top) | top | Returned |
|---|---|---|---|
| push(5) | 5 | 0 | Nothing |
| push(8) | 5, 8 | 1 | Nothing |
| pop() | 5 | 0 | 8 |
| push(3) | 5, 3 | 1 | Nothing |
| Operation | Queue (front to rear) | front | rear | Returned |
|---|---|---|---|---|
| enqueue(5) | 5 | 0 | 0 | Nothing |
| enqueue(8) | 5, 8 | 0 | 1 | Nothing |
| dequeue() | 8 | 1 | 1 | 5 |
| enqueue(3) | 8, 3 | 1 | 2 | Nothing |
In the queue above, space at the front of the array is never used again. A circular queue solves this by letting the pointers wrap round to index 0, using rear = (rear + 1) MOD maxSize.
Linked List Algorithms
// Traverse the list to search for an item
function search(toFind):
currentNode = headPointer
while currentNode != NULL:
if linkedList[currentNode].data == toFind then
return currentNode
end if
currentNode = linkedList[currentNode].pointer
end while
return -1
end function
| Operation | Steps |
|---|---|
| Traverse | Start at headPointer, process the node, then follow its pointer to the next node; stop when the pointer is NULL |
| Add an item | Store the data in the node that freeListPointer points to and move freeListPointer on to the next free node; follow the pointers from headPointer to find where the item belongs; set the new node's pointer to the node that will follow it; change the pointer of the node before it to point to the new node |
| Remove an item | Follow the pointers from headPointer to find the node; change the pointer of the node before it to the node after it, so that the list passes over the removed node; add the removed node to the free list |
Before: headPointer = 1 and freeListPointer = 3. Following the pointers gives Ant, Cat, Fox.
| Index | Data | Pointer |
|---|---|---|
| 0 | Cat | 2 |
| 1 | Ant | 0 |
| 2 | Fox | NULL |
| 3 | (free) | 4 |
| 4 | (free) | NULL |
| Index | Data | Pointer |
|---|---|---|
| 0 | Cat | 3 |
| 1 | Ant | 0 |
| 2 | Fox | NULL |
| 3 | Dog | 2 |
| 4 | (free) | NULL |