Stacks and Queues
Queue from Two Stacks
Implement queue behavior with an input stack and an output stack.
Algorithm
The replay uses the same three values in every language, so this R DSA implementation can be compared directly with the rest of the DSA track.
input stack
Enqueue pushes new values onto the input stack.
output stack
When the output stack is empty, transferring all input values reverses them into dequeue order.
Visual walkthrough
Basic Implementation
basic.R
render <- function(values) {
paste(values, collapse = " -> ")
}
in_stack <- c()
out_stack <- c()
for (value in c(10, 20, 30)) in_stack <- c(in_stack, value)
while (length(in_stack) > 0) {
out_stack <- c(out_stack, in_stack[length(in_stack)])
in_stack <- in_stack[-length(in_stack)]
}
removed <- c()
while (length(out_stack) > 0) {
removed <- c(removed, out_stack[length(out_stack)])
out_stack <- out_stack[-length(out_stack)]
}
cat(render(removed), "\n", sep = "")
Complexity
- Time: O(1) amortized per operation
- Space: O(n)
Implementation notes
in_stack <- c()andout_stack <- c()start as empty R vectors.- Enqueue appends onto the input stack with
in_stack <- c(in_stack, value)for the pinned values10,20, and30. - After enqueue, the trace shows
in_stack = [10, 20, 30]andout_stack = []. - This source treats the right end of each vector as the stack top.
- Transfer runs while
length(in_stack) > 0. in_stack[length(in_stack)]reads the top value from the input stack.out_stack <- c(out_stack, in_stack[length(in_stack)])pushes that value to the output stack.in_stack <- in_stack[-length(in_stack)]removes the old top by negative indexing.- The transfer reverses the stack, producing
out_stack = [30, 20, 10]and emptyingin_stack. - Dequeue then pops from the right end of
out_stackwithout_stack[length(out_stack)]. - Each popped scalar is appended to
removedwithremoved <- c(removed, ...).
Replay steps
start: in [], out [], removed []
enqueue: in [10, 20, 30], out []
transfer: in [], out [30, 20, 10]
dequeue: out [], removed [10, 20, 30]
render(removed)usespaste(values, collapse = " -> "), andcat(render(removed), "\n", sep = "")prints10 -> 20 -> 30.