Golang实现一个简单的单链表

Golang实现一个简单的单链表

package list

type Node struct {
	Data interface{}
	Next *Node
}

type List struct {
	size uint32
	head *Node
	tail *Node
}

// 构造方法,将所有变量置空
func (list *List) init() {
	(*list).size = 0
	(*list).head = nil
	(*list).tail = nil
}

func (list *List) Append(node *Node) bool {
	// 若 node 为空,直接返回
	if nil == node {
		return false
	}

	// 若 List 没有节点--头插
	// 若 List 存在节点--尾插
	if 0 == (*list).size {
		(*list).head = node
	} else {
		oldTail := (*list).tail
		(*oldTail).Next = node
	}

	(*list).tail = node
	(*list).size++

	return true
}

func (list *List) Insert(index uint32, node *Node) bool {
	if nil == node || index >= (*list).size || 0 == (*list).size {
		return false
	}

	// 如果 index 为0--头插
	if 0 == index {
		(*node).Next = (*list).head
		(*list).head = node
	} else {
		preNode := (*list).head
		for i := 1; uint32(i) < index; i++ {
			preNode = (*preNode).Next
		}

		(*node).Next = (*preNode).Next
		(*preNode).Next = node
	}

	(*list).size++
	return true
}

func (list *List) Remove(index uint32) bool {
	if index >= (*list).size {
		return false
	}

	if 0 == index { // 头删
		(*list).head = (*list).head.Next
		if 1 == (*list).size {
			(*list).tail = nil
		}
	} else {
		preNode := (*list).head
		for i := 1; uint32(i) < index; i++ {
			preNode = (*preNode).Next
		}
		(*preNode).Next = (*preNode).Next.Next

		if index == (*list).size- 2 {
			(*list).tail = preNode
		}
	}

	(*list).size--

	return true
}

func (list *List) IndexOf(index uint32) *Node {
	if index >= (*list).size {
		return nil
	}

	node := (*list).head
	for i := 0; uint32(i) < index; i++ {
		node = (*node).Next
	}

	return node
}

func (list *List) Size() uint32 {
	return (*list).size
}

func (list *List) Head() *Node {
	return (*list).head
}

func (list *List) Tail() *Node {
	return (*list).tail
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值