单链表

221 阅读1分钟

单链表是基本数据结构,经过适配可以用于实现栈和队列。

单链表基本实现

该单链表在适配后可以实现栈(Stack)

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

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

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

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
}

在基本实现基础上增加一个尾节点

该实现中加了一个尾节点和一个函数AddToTail,目的是便于实现单向队列(queue)

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

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

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

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
	}
}

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
	}
}