From a23ed05d93236cc6f84851ebddc7460cbf080ce4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=91=A8=E6=98=9F=E6=98=9F=E2=9C=A8?= Date: Tue, 29 Apr 2025 07:49:24 +0800 Subject: [PATCH] :bug: fix(go/09_queue): Fix the linked list queue. When all of the nodes are dequeue, keep the head and tail the same. --- go/09_queue/QueueBasedOnLinkedList.go | 7 +++++++ go/09_queue/QueueBasedOnLinkedList_test.go | 23 ++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/go/09_queue/QueueBasedOnLinkedList.go b/go/09_queue/QueueBasedOnLinkedList.go index 65d898da..5e017b61 100644 --- a/go/09_queue/QueueBasedOnLinkedList.go +++ b/go/09_queue/QueueBasedOnLinkedList.go @@ -33,8 +33,15 @@ func (this *LinkedListQueue) DeQueue() interface{} { if this.head == nil { return nil } + v := this.head.val this.head = this.head.next + + // fix: keep the head and tail the same + if this.head == nil { + this.tail = nil + } + this.length-- return v } diff --git a/go/09_queue/QueueBasedOnLinkedList_test.go b/go/09_queue/QueueBasedOnLinkedList_test.go index 425c6e8a..d45ca8b3 100644 --- a/go/09_queue/QueueBasedOnLinkedList_test.go +++ b/go/09_queue/QueueBasedOnLinkedList_test.go @@ -22,14 +22,37 @@ func TestListQueue_DeQueue(t *testing.T) { q.EnQueue(5) q.EnQueue(6) t.Log(q) + + // 1 + q.DeQueue() + t.Log(q) + + // 2 + q.DeQueue() + t.Log(q) + + // 3 q.DeQueue() t.Log(q) + + // 4 q.DeQueue() t.Log(q) + + // 5 q.DeQueue() t.Log(q) + + // 6 note: all of the nodes are dequeue + // head = tail = nil q.DeQueue() t.Log(q) + + // enqueue + q.EnQueue(1) + t.Log(q) + + // head = tail = nil q.DeQueue() t.Log(q) }