Senior
Explain the difference between LIFO and FIFO using the example of a stack and a queue.
sobes.tech AI
Answer from AI
LIFO (Last In, First Out) and FIFO (First In, First Out) are two methods of organizing data.
- LIFO — last arrived, first out. Example: stack. The most recently added element is retrieved first.
- FIFO — first arrived, first out. Example: queue. Elements are retrieved in the order they were added.
Example in Go:
package main
import "fmt"
func main() {
// Stack (LIFO)
stack := []int{}
stack = append(stack, 1) // push
stack = append(stack, 2)
fmt.Println("Stack:", stack)
top := stack[len(stack)-1]
stack = stack[:len(stack)-1] // pop
fmt.Println("Popped element (LIFO):", top)
// Queue (FIFO)
queue := []int{1, 2, 3}
fmt.Println("Queue:", queue)
first := queue[0]
queue = queue[1:] // dequeue
fmt.Println("Dequeued element (FIFO):", first)
}
In this example, the stack retrieves the last added element, while the queue retrieves the first.