Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 13

Stacks

Ref.: D.S. Malik, Data Structures Using C++

Stacks

a stack

an empty stack

Stacks
push adding an item to the top of a stack peek looking at the item on the top pop removing an item from the top of a stack

Implementation of Stacks as Arrays


maxStackSize the maximum number of elements that a stack can hold stackTop the top of the stack e.g. stackTop = 4

[3] [2] [1] [0]

Useful operations
Initialise Stack makes the stack an empty stack Is Stack Empty? checks to see whether stackTop = 0 Is Stack Full? - checks to see whether stackTop = maxStackSize

Useful operations
Push if stack is not full then {add an item to position [stackTop] increment stackTop} Peek if stack is not empty then output item at [stackTop] Pop if stack is not empty then decrement stackTop

Linked Implementation of Stacks


C stackTop A stack. Top element is C B A

stackTop An empty stack.

Useful operations - Initialise stack


C stackTop temp C B stackTop B stackTop A A loop until stackTop = NULL B A

temp C delete temp

Useful operations
Is Stack Empty? Check to see if stackTop = NULL Is Stack Full? Do not need this operation

Useful operations Push, step 1


C stackTop D newNode B A

Useful operations Push, steps 2 & 3


C stackTop D newNode B A

D stackTop

newNode

Useful operations
Peek if stack is not empty then return stackTop->info

Useful operations - Pop


C stackTop temp C B stackTop B stackTop A A B A

temp C delete temp

You might also like