0% found this document useful (0 votes)
27 views

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

Stacks can be implemented using arrays or linked lists. With arrays, a stack is represented by maxStackSize, stackTop, and the array elements. Operations like push add elements to index stackTop and increment stackTop. Pop removes the element at stackTop and decrements stackTop. Linked list implementation uses a stackTop pointer, with push adding a new node after stackTop and pop removing and deleting the node at stackTop.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

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

Stacks can be implemented using arrays or linked lists. With arrays, a stack is represented by maxStackSize, stackTop, and the array elements. Operations like push add elements to index stackTop and increment stackTop. Pop removes the element at stackTop and decrements stackTop. Linked list implementation uses a stackTop pointer, with push adding a new node after stackTop and pop removing and deleting the node at stackTop.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 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