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

96 阅读1分钟

之前实现的基础上调整单链表和队列的接口。 将size变量移到list中。

type Queue struct {
	list *SinglyLinkedList
}

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

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

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

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

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()
	return node.V
}

// 单链表节点
type SLLNode struct {
	V interface{}
	Next *SLLNode
}

// 单链表
type SinglyLinkedList struct {
	head *SLLNode
	tail *SLLNode // 尾节点。使得在尾部添加节点的时间复杂度是O(1)
        size int
}

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

func (o *SinglyLinkedList) AddToHead(v interface{}) {
	o.head = &SLLNode{
		V: v,
        Next: o.head,
	}
	if o.tail == nil {
		o.tail = o.head
	}
        o.size++
}

func (o *SinglyLinkedList) Head() *SLLNode {
	return o.head
}

func (o *SinglyLinkedList) RemoveHead() {
	if o.head == nil {
		panic("SinglyLinkedList. head is nil")
	}
	o.head = o.head.Next
	if o.head == nil {
		o.tail = nil
	}
        o.size--
}

func (o *SinglyLinkedList) AddToTail(v interface{}) {
	node := &SLLNode{
		V: v,
	}
	if o.tail != nil {
		o.tail.Next = node
		o.tail = node
	} else {
		o.head = node
        o.tail = node
	}
        o.size++
}