package main
import (
"fmt"
)
// QueueUsingStacks struct holds two stacks for queue implementation
type QueueUsingStacks struct {
inputStack []int // Stack for enqueue operations
outputStack []int // Stack for dequeue operations
}
// Enqueue adds a new value to the queue
func (qs *QueueUsingStacks) Enqueue(value int) {
qs.inputStack = append(qs.inputStack, value) // Push value onto the input stack
}
// dequeueFromInput transfers all elements from the input stack to the output stack
func (qs *QueueUsingStacks) dequeueFromInput() {
// Transfer elements to reverse their order for FIFO behavior
for len(qs.inputStack) > 0 {
top := qs.inputStack[len(qs.inputStack)-1] // Get the top element
qs.inputStack = qs.inputStack[:len(qs.inputStack)-1] // Remove top element from input stack
qs.outputStack = append(qs.outputStack, top) // Push it onto the output stack
}
}
// Dequeue removes and returns the front element of the queue
func (qs *QueueUsingStacks) Dequeue() int {
// If output stack is empty, transfer elements from input stack
if len(qs.outputStack) == 0 {
qs.dequeueFromInput()
}
// Return the top element from the output stack if available
if len(qs.outputStack) > 0 {
top := qs.outputStack[len(qs.outputStack)-1] // Get the front element
qs.outputStack = qs.outputStack[:len(qs.outputStack)-1] // Remove it from output stack
return top // Return the dequeued value
}
return -1 // Return -1 if the queue is empty
}
func main() {
queue := &QueueUsingStacks{} // Create a new queue instance
// Enqueue elements
queue.Enqueue(10)
queue.Enqueue(20)
queue.Enqueue(30)
fmt.Println("Three elements are enqueued in the following order: 10, 20, and 30.")
fmt.Println("\nNow, let's dequeue three times!")
// Dequeue elements and print the results
fmt.Println("\nDequeue:", queue.Dequeue()) // Should print 10
fmt.Println("Dequeue:", queue.Dequeue()) // Should print 20
fmt.Println("Dequeue:", queue.Dequeue()) // Should print 30
}