03 Stack and Queue Data Structures1

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 5

Stack and Queue Data Structures

Stack and Queue Data Structures


• Both are lists of items that are retrieved in different orders
• Stack is “Last in First Out” or LIFO because when you remove
an item you get the most recently added item.
• Queue is “First in First Out” or FIFO because when you remove
an item you get the item that has been waiting the longest.
Stack Operations
• Push(item) – Adds the item to the ‘top’ of the stack.
• Pop() – Removes the item at the top of the stack and returns it.
• IsEmpty() – Returns True if there are no items in the stack.
Optional Operations:
• Top() – Returns the item at the top of the stack without
removing it from the stack, sometimes called Peek().
• IsFull() – If the stack has been implemented with a size limit,
this method returns True when the stack is full.
Stack Uses
• Remembering Partially completed tasks
– Calculator Registers
– Computer Program Function Calls
• Undoing or Backtracking completed actions
– Undo function in Word. All edits are added to a stack and the undo
removes the last edit and reverses it
– Artificial Intelligence search algorithms sometimes explore different
paths and can use a Stack to backtrack if a path is found to be a bad
one.
Stack Example
• Create Empty Stack with room for 3 items, Count = 0
_____
_____
_____

• Push item on stack with push(56); Count = 1


_____
_____
__56_

• Push another item on stack with push(123); Count = 2


_____
__123
___56

• Pop an item from stack with pop() which will return 123, Count = 1
_____
_____
___56

• Push 2 items with calls to push(45); followed by push(87); Count = 3 stack full
___87
___45
___56

• Three calls to pop(); return 87, 45, and 56 in order, and empty the stack

You might also like