使用链表实现队列(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)
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值