Stacks and Queues
Queue Enqueue/Dequeue
Enqueue values at the back and dequeue them from the front in first-in, first-out order.
Algorithm
Basic Implementation
basic.R
render <- function(values) {
paste(values, collapse = " -> ")
}
queue <- c()
for (value in c(10, 20, 30)) queue <- c(queue, value)
removed <- c()
while (length(queue) > 0) {
removed <- c(removed, queue[1])
queue <- queue[-1]
}
cat(render(removed), "\n", sep = "")
Complexity
- Time: O(1) per operation with a real queue
- Space: O(n)
Implementation notes
queue <- c()starts an empty R vector used as the queue.- Enqueue uses
queue <- c(queue, value)insidefor (value in c(10, 20, 30)), appending each value at the back. - After those three appends, the trace shows
queue = [10, 20, 30]. removed <- c()starts a second vector for the values returned by dequeue.- The loop runs while
length(queue) > 0. - R vectors are 1-based, so the front value is
queue[1]. - Dequeue records that scalar with
removed <- c(removed, queue[1]). - The line
queue <- queue[-1]removes the first element by negative indexing, leaving the remaining vector as the new queue.
Replay steps
start: queue [], removed []
enqueue all: queue [10, 20, 30]
dequeue 10: queue [20, 30], removed [10]
dequeue rest: queue [], removed [10, 20, 30]
render(removed)usespaste(values, collapse = " -> ").cat(render(removed), "\n", sep = "")prints10 -> 20 -> 30.
front
The front is the oldest value still waiting in the queue.
FIFO
A queue removes values in first-in, first-out order.