使用鏈表實現隊列(Golang)

package queue

type Queue struct {
	head *QueueNode
	tail *QueueNode
}

type QueueNode struct {
	data interface{}
	next *QueueNode
}

func NewQueue() (q *Queue) {
	head := QueueNode{}
	return &Queue{&head, &head}
}

func (q *Queue) Push(data ...interface{}) {
	if q == nil || q.tail == nil {
		return
	}

	for _, d := range data {
		node := &QueueNode{data: d, next: nil}
		q.tail.next = node
		q.tail = node
	}
}

func (q *Queue) Pop() interface{} {
	if q == nil || q.head == nil || q.head == q.tail {
		return nil
	}

	if q.head.next == q.tail {
		q.tail = q.head
	}
	data := q.head.next.data
	q.head.next = q.head.next.next
	return data
}

測試代碼:

package queue

import (
	"testing"
)

func TestNewQueue(t *testing.T) {
	q := NewQueue()
	if q == nil || q.head == nil || q.head != q.tail {
		t.Fatalf("NewQueue error: %v %v %v", q, q.head, q.tail)
	}
}

func TestPushInt(t *testing.T) {
	q := NewQueue()
	q.Push(1, 2, 3, 4)
	want := []int{1, 2, 3, 4}
	got := []int{}
	for {
		d := q.Pop()
		if d == nil {
			break
		}
		got = append(got, d.(int))
	}
	if len(got) != len(want) {
		t.Fatalf("Push/Pop assert failure, want %v, got %v\n", want, got)
	}
	for i := 0; i < len(want); i++ {
		if want[i] != got[i] {
			t.Errorf("Push/Pop assert failure, want %v, got %v\n", want, got)
		}
	}
}

func TestPushString(t *testing.T) {
	q := NewQueue()
	q.Push("1", "22", "3", "AA")
	q.Push("BBB")
	want := []string{"1", "22", "3", "AA", "BBB"}
	got := []string{}
	for {
		d := q.Pop()
		if d == nil {
			break
		}
		got = append(got, d.(string))
	}
	if len(got) != len(want) {
		t.Fatalf("Push/Pop assert failure, want %v, got %v\n", want, got)
	}
	for i := 0; i < len(want); i++ {
		if want[i] != got[i] {
			t.Errorf("Push/Pop assert failure, want %v, got %v\n", want, got)
		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章