# golang 系列教程（四）-高级数据结构

golang 不像c++，已经有stl这种通用的高级数据结构。所以如果想要栈，队列，链表等数据结构需要自己实现。

## 链表

package list

type List struct {
length int
}

type ListNode struct {
Next *ListNode
Data int
}

func (p *List) AddNode(data int) {
if p.Head == nil {
}
var node = &ListNode {
Data : data,
}
node.Next = currentNext
}

func (p *List) Lenth() int {
return p.length
}

// delete specified pos
func (p *List) DeleteWithPos(pos int) {
if pos + 1 >  p.length {
return
}
var i int
for {
if i == pos {
pre.Next = pre.Next.Next
}
pre = pre.Next
i++
}
return
}

func (p *List) DeleteWithData(data int) {
for {
if pre.Next == nil {
break
}
if data == pre.Next.Data {
pre.Next = pre.Next.Next
}
pre = pre.Next
}
return
}

## 队列

package queue

import (
"errors"
)

type Queue []interface{}

func (queue *Queue) Len() int {
return len(*queue)
}

func (queue *Queue) IsEmpty() bool {
return len(*queue) == 0
}

func (queue *Queue) Cap() int {
return cap(*queue)
}

func (queue *Queue) Push(value interface{}) {
*queue = append(*queue, value)
}

func (queue *Queue) Pop() (interface{}, error) {
theQueue := *queue
if len(theQueue) == 0 {
return nil, errors.New("Out of index, len is 0")
}
value := theQueue[0]
*queue = theQueue[1:len(theQueue)]
return value, nil
}

## 栈

package stack

import "errors"

type Stack []interface{}

func (stack Stack) Len() int {
return len(stack)
}

func (stack Stack) IsEmpty() bool {
return len(stack) == 0
}

func (stack Stack) Cap() int {
return cap(stack)
}

func (stack *Stack) Push(value interface{}) {
*stack = append(*stack, value)
}

func (stack Stack) Top() (interface{}, error) {
if len(stack) == 0 {
return nil, errors.New("Out of index, len is 0")
}
return stack[len(stack)-1], nil
}

func (stack *Stack) Pop() (interface{}, error) {
theStack := *stack
if len(theStack) == 0 {
return nil, errors.New("Out of index, len is 0")
}
value := theStack[len(theStack)-1]
*stack = theStack[:len(theStack)-1]
return value, nil
}