数据结构和算法-队列

120 阅读1分钟

定义

队列是一种操作受限的线性表结构,只能在一端插入,在另一端删除元素,故有先入先出特征,可以用链表或者数组实现。

算法

队列包含的操作有两个,时间和空间复杂度应该为O(1)

  1. 入队列
  2. 出队列

应用场景

任何有先入先出的需求场景都可以使用队列

实现

数组

以下数组实现的队列,出队列操作是删除index=0的元素,需要搬迁数据,所以时间复杂度为O(n);入队列添加元素到数组尾部,所以时间复杂度为O(1)。

type ArrayQueue struct {
    Vals []int
}

func NewArrayQueue() ArrayQueue {
    return ArrayQueue{}
}

func (this *ArrayQueue) Offer(val int) {
    this.Vals = append(this.Vals, val)
}

func (this *ArrayQueue) Poll() int {
    if len(this.Vals) == 0 {
	return -1
    }
    val := this.Vals[0]
    this.Vals = this.Vals[1:len(this.Vals)]
    return val
}

链表

链表实现的队列,入栈和出栈的时间复杂度都为O(1)

type QueueNode struct {
    Val  int
    Next *QueueNode
    Pre  *QueueNode
}

type LinkedQueue struct {
    Head *QueueNode
    Tail *QueueNode
}

func NewLinkedQueue() LinkedQueue {
    return LinkedQueue{}
}

func (this *LinkedQueue) Offer(val int) {
    node := &QueueNode{Val: val}
    node.Next = this.Tail
    if this.Tail != nil {
	this.Tail.Pre = node
    }
    this.Tail = node
    if this.Head == nil {
	this.Head = this.Tail
    }
}

func (this *LinkedQueue) Poll() int {
    if this.Head == nil {
	return -1
    }
    val := this.Head.Val
    this.Head = this.Head.Pre
    if this.Head != nil {
        this.Head.Next = nil
    }
    return val
}