数据结构:栈(二)

176 阅读1分钟

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

type Stack struct {
	list *SinglyLinkedList
}

func NewStack() *Stack {
	return &Stack{
		list: &SinglyLinkedList{},
	}
}

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

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

func (o *Stack) Push(v interface{}) {
	o.list.AddToHead(v)
}

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

func (o *Stack) Pop() {
	if o.IsEmpty() {
		panic("Stack is empty")
	}
	o.list.RemoveHead()
}

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

// 单链表
type SinglyLinkedList struct {
	head *SLLNode
        size int
}

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

func (o *SinglyLinkedList) AddToHead(v interface{}) {
	o.head = &SLLNode{
		V: v,
                Next: 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
        o.size--
}