Stacks and Queues Flashcards
Stacks
A stack of data. Last-in first-out ordering. It uses pop, push, peek and isEmpty. No constant-time access to ith item, but constant-time for adds and removes. Good for recursive algorithms.
pop()
Remove the top item from a stack
push(item)
Add an item to the top of the stack
peek()
Return the top of the stack or first in the queue
isEmpty()
Return true if and only if the stack/queue is empty.
Implementing a stack
A Stack class contains a static StackNode inner class with data and next fields. The Stack class contains a top field, and a pop, push, peek and isEmpty method. They can be implemented as linked list if items are added and removed from the same side: null .– node 1 .– node 2 .– … .– top
implement pop()
Ensure stack is not empty. Collect top node’s data. Set top to top.next. Return popped data.
implement push()
Create new node. Set new node next to top. Set top to new node.
implement peek()
Ensure stack or queue is not empty. return top.data or first.data.
implement isEmpty
return true if top or first is null.
Queue
First-in first-out ordering. Items are removed from the data structure in the same order that they are added. It uses add, remove, peek, and isEmpty methods. Good for caches and breadth first searches.
add(item)
Add an item to the end of the queue
remove()
Remove the first item from the queue
Implementing a queue
A queue class contains a inner static QueueNode class with a data and next field. The Queue class has first and last fields and add, remove, peek and isEmpty methods. A queue can be implemented as a linked list with items added and removed from opposite sides: first–>1–>2–>…–>last–>null.
Implement add(item) (Linked Lists)
Create new node. If last not null, last.next is new node. Last becomes new node. If first is null, first becomes last.