Stacks and Queues
Stack Push/Pop
Push values onto a stack and pop them back in last-in, first-out order.
Algorithm
Basic Implementation
basic.R
render <- function(values) {
paste(values, collapse = " -> ")
}
stack <- c()
for (value in c(10, 20, 30)) stack <- c(stack, value)
popped <- c()
while (length(stack) > 0) {
popped <- c(popped, stack[length(stack)])
stack <- stack[-length(stack)]
}
cat(render(popped), "\n", sep = "")
Complexity
- Time: O(1) per push/pop
- Space: O(n)
Implementation notes
stack <- c()starts as an empty R vector, and the lesson uses the right end of that vector as the stack top.- The pinned push loop appends
10,20, and30withstack <- c(stack, value), so the trace moves from[]to[10, 20, 30]. - Pop reads the top scalar with
stack[length(stack)], then removes that slot withstack <- stack[-length(stack)]. - Each removed value is appended to
poppedwithpopped <- c(popped, ...), so the replay records[30]first and finishes with[30, 20, 10].
Replay steps
start: stack [], popped []
push: stack [10, 20, 30]
pop 30: stack [10, 20], popped [30]
pop all: stack [], popped [30, 20, 10]
render(popped)usespaste(values, collapse = " -> "), andcat(render(popped), "\n", sep = "")prints30 -> 20 -> 10.
top
The top is the most recently pushed value.
LIFO
A stack removes values in last-in, first-out order.