Stacks and Queues Flashcards
1
Q
stack
A
- data structure similar to a list with access restricted to only 1 end.
- It stores elements in a LIFO order.
- thought of as vertical data structures
- 2 functions
1. push()
2. pop()
2
Q
LIFO
A
Last In First Out
3
Q
standard stack initiation
A
class Stack { constructor() { this.top = null; }
4
Q
push()
A
places data onto the top of a stack
5
Q
pop()
A
removes data from the top of the stack
6
Q
standard push()
A
push(data) { /* If the stack is empty, then the node will be the top of the stack */ if (this.top === null) { this.top = new _Node(data, null); return this.top; }
/* If the stack already has something, then create a new node, add data to the new node, and have the pointer point to the top */ const node = new _Node(data, this.top); this.top = node; }
7
Q
standard pop()
A
pop() { /* In order to remove the top of the stack, you have to point the pointer to the next item and that next item becomes the top of the stack */ const node = this.top; this.top = node.next; return node.data; }
8
Q
queue
A
data structure that models a FIFO operation
2 functions:
1. enqueue(data)
2. dequeue()
9
Q
FIFO
A
First In First Out
10
Q
standard queue initiation
A
class Queue { constructor() { this.first = null; this.last = null; }
11
Q
enqueue(data)
A
adds data to a queue (insertion)
12
Q
dequeue()
A
removes the oldest data added to a queue (deletion)
13
Q
standard enqueue
A
enqueue(data) { const node = new _Node(data);
if (this.first === null) { this.first = node; }
if (this.last) { this.last.next = node; } //make the new node the last item on the queue this.last = node; }
14
Q
standard dequeue
A
dequeue() { //if the queue is empty, there is nothing to return if (this.first === null) { return; } const node = this.first; this.first = this.first.next; //if this is the last item in the queue if (node === this.last) { this.last = null; } return node.value; }