Ch 3: Stacks and Queues Flashcards
1
Q
Stacks and Queues:
Important Data Structures
A
- Stack
- Queue
- Array
- Multi-Stack
- Priority Queue
2
Q
Stacks and Queues:
Important Concepts/Operations
A
- FIFO Ordering
- LIFO Ordering
- Implementing a Stack with an Array
- Implementing a Queue with Stacks
- Sorting Stacks
3
Q
Stack:
Basic Description
A
- Data is stored as a “stack”, similar to a physical stack of dinner plates
- Uses Last-In, First Out (LIFO) ordering
- The most recently added item is the first removed
- Allows constant-time adds and removes, but linear-time access to nth item
4
Q
Stack:
Defining Operations
A
- pop()
- push(item)
- peek()
- isEmpty()
5
Q
Stack Operations:
pop()
A
Removes and returns the top item from the stack
6
Q
Stack Operations:
push( item)
A
Adds an item to the top of the stack
7
Q
Stack Operations:
peek()
A
Returns, but does not remove, the top item of the stack
8
Q
Stack Operations:
isEmpty()
A
Returns true iff the stack is empty
9
Q
Stacks:
Time Complexity
A
- O(i) time to access the ith item
- Need to pop everything above it
- O(1) time for adding and removing items
10
Q
Uses for Stacks
A
- Storing temporary data for recursive algorithms, allows going “backward” by popping items off on the way back ‘up”
- Implementing recursive algorithms iteratively
11
Q
Stack Implementation:
Basic Structure
A
public class MyStack<T> { private static class StackNode<T> { private T data; private StackNode<T> next; public StackNode(T data){}; } private StackNode<T> top; public T pop(){} public void push(T item){} public T peek(){} public boolean isEmpty(){} }
12
Q
Stack Implementation:
pop() method
A
public T pop() { if (top == null) throw new EmptyStackException(); T item = top.data; top = top.next; return item; }
13
Q
Stack Implementation:
push() method
A
public void push(T item) { StackNode<T> node = new StackNode<T>(item); node.next = top; top = node; }
14
Q
Stack Implementation:
peek() method
A
public T peek() { if (top == null) throw new EmptyStackException(); return top.data; }
15
Q
Stack Implementation:
isEmpty() method
A
public boolean isEmpty() { return top == null; }