(6)Go实现链表队列


用链表实现队列的思路如上图,这样插入和取出操作时间复杂度都是O(1)

// 链表实现队列的方法定义
type node struct {
	Item interface{}
	Next *node
}

type linkedListQueue struct {
	Length int
	head   *node //头节点
	tail   *node //尾节点
}

func NewNode() *node {
	return &node{
		Item: nil,
		Next: nil,
	}
}

func NewLinkedListQueue() *linkedListQueue {
	return &linkedListQueue{
		Length: 0,
		head:   nil,
		tail:   nil,
	}
}

func (l *linkedListQueue) IsEmpty() bool {
	return l.Length == 0
}

func (l *linkedListQueue) Len() int {
	return l.Length
}

func (l *linkedListQueue) Enqueue(item interface{}) {
	buf := &node{
		Item: item,
		Next: nil,
	}
	if l.Length == 0 {
		l.tail = buf
		l.head = buf

	} else {
		l.tail.Next = buf
		l.tail = l.tail.Next
	}
	l.Length++
}

func (l *linkedListQueue) Dequeue() (item interface{}) {
	if l.Length == 0 {
		return errors.New(
			"failed to dequeue, queue is empty")
	}

	item = l.head.Item
	l.head = l.head.Next

	// 当只有一个元素时,出列后head和tail都等于nil
	// 这时要将tail置为nil,不然tail还会指向第一个元素的位置
	// 比如唯一的元素原本为2,不做这步tail还会指向2
	if l.Length == 1 {
		l.tail = nil
	}

	l.Length--
	return
}

func (l *linkedListQueue) Traverse() (resp []interface{}) {
	buf := l.head
	for i := 0; i < l.Length; i++ {
		resp = append(resp, buf.Item, "<--")
		buf = buf.Next
	}
	return
}

func (l *linkedListQueue) GetHead() (item interface{}) {
	if l.Length == 0 {
		return errors.New(
			"failed to getHead, queue is empty")
	}
	return l.head.Item
}
// 测试结果
func main() {
	q := linked_list3.NewLinkedListQueue()

	for i := 0; i < 5; i++ {
		q.Enqueue(i)
		fmt.Println(q.Traverse())
	}

	fmt.Println(q.GetHead(), q.Len(), q.IsEmpty())

	for i := 0; i < 5; i++ {
		q.Dequeue()
		fmt.Println(q.Traverse())
	}
}
// 输出结果
[0 <--]
[0 <-- 1 <--]
[0 <-- 1 <-- 2 <--]
[0 <-- 1 <-- 2 <-- 3 <--]
[0 <-- 1 <-- 2 <-- 3 <-- 4 <--]
0 5 false
[1 <-- 2 <-- 3 <-- 4 <--]
[2 <-- 3 <-- 4 <--]
[3 <-- 4 <--]
[4 <--]
[]

链表实现的队列插入和取出操作时间复杂度都是O(1),相比切片构成循环队列在理论上更有优势。
不过并不代表链表构成的队列一定更好,链表花时间的地方主要是在创建新节点上,如果一个场景中,插入操作很多,取出操作很少,由切片构成队列可能运算更快。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值