Stacks
 

A Stack is a LIFO (Last In First Out) Data structure - like a stack of plates being washed - a new plate gets placed on the top of the stack, and if one is removed, it is also removed from the top.

With every stack there is a stack pointer showing where the top of the stack is. 

Example : The diagram shows a stack with three data items already in it. :  

8   STACK POINTER = 3
7  
6  
5  
4  
3 TODDS
2 JONES
1 GUDRUNSON

 

If a new name 'EGBERT' is added to (pushed onto) the stack, the new stack looks like......

8  

STACK POINTER =4

7  
6  
5  
4 EGBERT
3 TODDS
2 JONES
1 GUDRUNSON

(Note that the Stack Pointer has been incremented).

 Stacks are very useful data structures in computing.. Uses include:

  • Storing return addresses. When a program is run and a subroutine is called, the address where the processing stopped is pushed onto a stack. The subroutine is run, and when completed, the processing returns to the address on the top of the stack (which is removed from the stack). This means that subroutines may call subroutines etc..
  • Stacks are also used to evaluate arithmetical expressions given in Reverse Polish Notation

 
 

Algorithms

Assume we have an array Key[1..StackPointer] of records.

The algorithm for adding another record called NewRecord onto the stack is..

Procedure Add(NewRecord)

if  (SP < MaxRecords)  then
    increment SP
    Key[SP] =
NewRecord
else output('Stack full')

SP is the Stack Pointer.

MaxRecords is the maximum number of records which can be stored in the stack.

The algorithm for popping a record from the stack is

Procedure Remove

if (SP > 0) then
    decrement StackPointer
else output('Stack empty')

Note : There is no need to 'delete' the record from the top of the stack. A new record pushed onto the stack would 'overwrite' any previous one.