|
| 1 | +// stack using queue |
| 2 | +package main |
| 3 | + |
| 4 | +import ( |
| 5 | + "container/list" |
| 6 | + "fmt" |
| 7 | +) |
| 8 | + |
| 9 | +// Stack represents a stack data structure using two queues. |
| 10 | +type Stack struct { |
| 11 | + queue1 *list.List // Primary queue |
| 12 | + queue2 *list.List // Temporary queue for operations |
| 13 | +} |
| 14 | + |
| 15 | +// Constructor creates a new stack. |
| 16 | +func NewStack() *Stack { |
| 17 | + return &Stack{ |
| 18 | + queue1: list.New(), |
| 19 | + queue2: list.New(), |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +// Push adds an element to the top of the stack. |
| 24 | +func (s *Stack) Push(value int) { |
| 25 | + // Add the element to the primary queue |
| 26 | + s.queue1.PushBack(value) |
| 27 | +} |
| 28 | + |
| 29 | +// Pop removes and returns the top element of the stack. |
| 30 | +func (s *Stack) Pop() int { |
| 31 | + // Move elements from the primary queue to the temporary queue except the last one |
| 32 | + for s.queue1.Len() > 1 { |
| 33 | + element := s.queue1.Front() |
| 34 | + s.queue1.Remove(element) |
| 35 | + s.queue2.PushBack(element.Value) |
| 36 | + } |
| 37 | + |
| 38 | + // Get the last element from the primary queue (top of the stack) |
| 39 | + topElement := s.queue1.Front().Value |
| 40 | + |
| 41 | + // Swap the primary and temporary queues |
| 42 | + s.queue1, s.queue2 = s.queue2, s.queue1 |
| 43 | + |
| 44 | + return topElement.(int) |
| 45 | +} |
| 46 | + |
| 47 | +// Top returns the top element of the stack without removing it. |
| 48 | +func (s *Stack) Top() int { |
| 49 | + // Similar to Pop, but don't remove the last element |
| 50 | + topElement := s.Pop() |
| 51 | + |
| 52 | + // Add the top element back to the stack |
| 53 | + s.Push(topElement) |
| 54 | + |
| 55 | + return topElement |
| 56 | +} |
| 57 | + |
| 58 | +// IsEmpty checks if the stack is empty. |
| 59 | +func (s *Stack) IsEmpty() bool { |
| 60 | + return s.queue1.Len() == 0 |
| 61 | +} |
| 62 | + |
| 63 | +func main() { |
| 64 | + stack := NewStack() |
| 65 | + |
| 66 | + // Push elements onto the stack |
| 67 | + stack.Push(1) |
| 68 | + stack.Push(2) |
| 69 | + stack.Push(3) |
| 70 | + |
| 71 | + // Pop elements from the stack |
| 72 | + fmt.Println(stack.Pop()) // Output: 3 |
| 73 | + fmt.Println(stack.Pop()) // Output: 2 |
| 74 | + |
| 75 | + // Push more elements |
| 76 | + stack.Push(4) |
| 77 | + stack.Push(5) |
| 78 | + |
| 79 | + // Peek at the top element |
| 80 | + fmt.Println(stack.Top()) // Output: 5 |
| 81 | + |
| 82 | + // Check if the stack is empty |
| 83 | + fmt.Println(stack.IsEmpty()) // Output: false |
| 84 | +} |
0 commit comments