Go语言队列实现

一、队列结构特点

队列是一种可以实现“先进先出”的存储结构。你可以把它想象成排队买票,先来的先买,后来的人只能站末尾,不允许插队。先进者先出,这就是典型的“队列

队列最基本的操作是两个:入队 enqueue(),放一个数据到队列尾部;出队 dequeue(),从队列头部取一个元素。
Go语言队列实现_第1张图片

二、Go语言队列实现

队列可以用数组来实现,也可以用链表来实现。用数组实现的栈叫作顺序栈,用链表实现的栈叫作链式栈。同样,用数组实现的队列叫作顺序队列,用链表实现的队列叫作链式队列

链式队列Go语言实现

package QueueBaseOnList

import (
	"fmt"
	"github.com/pkg/errors"
)

type ListNode struct {
	data interface{}
	next *ListNode
}

type LinkListNode struct {
	head  	*ListNode
	tail  	*ListNode
	length  int
}

func NewLinkListNode()*LinkListNode{
	return &LinkListNode{
		head:nil,
		tail:nil,
		length:0,
	}
}

func (this *LinkListNode)Enque(v interface{}){
	node := &ListNode{v,nil}

	if this.head == nil {
		this.head = node
		this.tail = node
	}else{
		this.tail.next = node
		this.tail = node
	}

	this.length++
}

func (this *LinkListNode)Deque()(interface{},error){
	if this.head == this.tail{
		return 0,errors.New("Queue Empty")
	}

	v := this.head.data
	this.head = this.head.next
	this.length--

	return v,nil
}

func (this LinkListNode)Print(){
	prev := this.head

	for prev != nil {
		fmt.Println(prev.data)

		prev = prev.next
	}
}


你可能感兴趣的:(数据结构和算法)