diff --git a/codes/go/chapter_stack_and_queue/array_deque.go b/codes/go/chapter_stack_and_queue/array_deque.go index 85d98aca5..37b436f2b 100644 --- a/codes/go/chapter_stack_and_queue/array_deque.go +++ b/codes/go/chapter_stack_and_queue/array_deque.go @@ -72,6 +72,9 @@ func (q *arrayDeque) pushLast(num int) { /* 队首出队 */ func (q *arrayDeque) popFirst() any { num := q.peekFirst() + if num == nil { + return nil + } // 队首指针向后移动一位 q.front = q.index(q.front + 1) q.queSize-- @@ -81,6 +84,9 @@ func (q *arrayDeque) popFirst() any { /* 队尾出队 */ func (q *arrayDeque) popLast() any { num := q.peekLast() + if num == nil { + return nil + } q.queSize-- return num } diff --git a/codes/go/chapter_stack_and_queue/array_queue.go b/codes/go/chapter_stack_and_queue/array_queue.go index 9068996a1..d8723e8e3 100644 --- a/codes/go/chapter_stack_and_queue/array_queue.go +++ b/codes/go/chapter_stack_and_queue/array_queue.go @@ -49,6 +49,10 @@ func (q *arrayQueue) push(num int) { /* 出队 */ func (q *arrayQueue) pop() any { num := q.peek() + if num == nil { + return nil + } + // 队首指针向后移动一位,若越过尾部,则返回到数组头部 q.front = (q.front + 1) % q.queCapacity q.queSize-- diff --git a/codes/go/chapter_stack_and_queue/queue_test.go b/codes/go/chapter_stack_and_queue/queue_test.go index cf46cd17b..c25f0f12d 100644 --- a/codes/go/chapter_stack_and_queue/queue_test.go +++ b/codes/go/chapter_stack_and_queue/queue_test.go @@ -46,9 +46,13 @@ func TestQueue(t *testing.T) { } func TestArrayQueue(t *testing.T) { + // 初始化队列,使用队列的通用接口 capacity := 10 queue := newArrayQueue(capacity) + if queue.pop() != nil { + t.Errorf("want:%v,got:%v", nil, queue.pop()) + } // 元素入队 queue.push(1)