数据结构:单向队列(Queue)

206 阅读1分钟

单向队列,先进先出(后进后出),常用数据结构之一。
广度优先遍历要基于该数据结构做模拟操作。

刷题常用。

实现一,基于go标准库的container/list

import "container/list"

type Queue struct {
	l *list.List
}

func NewQueue() *Queue {
	return &Queue{
		l: list.New(),
	}
}

func (o *Queue) Push(v interface{}) {
	o.l.PushBack(v)
}

func (o *Queue) Pop() interface{} {
	if o.IsEmpty() {
		panic("Queue is empty")
	}
	e := o.l.Front()
	o.l.Remove(e)
	return e.Value
}

func (o *Queue) Front() interface{} {
	if o.IsEmpty() {
		panic("Queue is empty")
	}
	return o.l.Front().Value
}

func (o *Queue) Back() interface{} {
	if o.IsEmpty() {
		panic("Queue is empty")
	}
	return o.l.Back().Value
}

func (o *Queue) IsEmpty() bool {
	return o.l.Len() == 0
}

func (o *Queue) Len() int {
	return o.l.Len()
}

实现二,基于单链表

// 导入单链表的package
import "algo/internal/singlylinkedlist"

type Queue struct {
	list *singlylinkedlist.SinglyLinkedList
	size int
}

func NewQueue() *Queue {
	return &Queue{
		list: &singlylinkedlist.SinglyLinkedList{},
	}
}

func (o *Queue) Len() int {
	return o.size
}

func (o *Queue) IsEmpty() bool {
	return o.size == 0
}

func (o *Queue) Push(v interface{}) {
	o.list.AddToTail(v)
	o.size++
}

func (o *Queue) Peek() interface{} {
	if o.IsEmpty() {
		panic("Queue is empty")
	}
	return o.list.Head().V
}

func (o *Queue) Pop() interface{} {
	if o.IsEmpty() {
		panic("Queue is empty")
	}
	node := o.list.Head()
	o.list.RemoveHead()
	o.size--
	return node.V
}

测试代码

package main

import "fmt"

func main() {
	q := NewQueue()
	for i := 0; i < 9; i++ {
		q.Push(i * 10)
	}
	for !q.IsEmpty() {
		fmt.Println(q.Front(),q.Back(),q.Len(),q.Pop().(int))
	}
}