Golang实现单链表

实现功能:

头插 尾插 根据Index增删改查 根据data求index 遍历打印 顺便再分享一个可视化数据结构网站:https://visualgo.net/zh

type Element int64

type ListNode struct {
	Data Element
	Next *ListNode
}

func newListNode(data Element) *ListNode {
	return &ListNode{Data: data}
}

func newHeader() *ListNode {
	return &ListNode{Data: 0, Next: nil,}
}

//从尾部插入
func TailAdd(head *ListNode, data Element) {
	point := head
	for point.Next != nil {
		point = point.Next
	}

	node := newListNode(data)
	point.Next = node
}

//从头部插入
func HeadAdd(head *ListNode, data Element) {
	point := head

	node := newListNode(data)
	node.Next = point.Next
	point.Next = node
}

//指定位置插入
func Insert(head *ListNode, index int, data Element) {
	if index < 0 || index > GetListLength(head) {
		fmt.Println("Index error,Please check again.")
		return
	}
	point := head
	for i := 0; i < index - 1 ; i++ {
		point = point.Next
	}

	node := newListNode(data)
	node.Next = point.Next
	point.Next = node
}

//删除指定Index元素
func Delete(head *ListNode, index int) {
	if index < 0 ||  index > GetListLength(head) {
		fmt.Println("Index error,Please check again.")
		return
	}

	point := head
	for i := 0; i < index - 1; i++ {
		point = point.Next
	}
	point.Next = point.Next.Next
}

// 查询元素的位置
func Search(head *ListNode, data Element) (index int) {
	point := head
	index = 0
	for point.Next != nil {
		if point.Data == data {
			fmt.Println(fmt.Sprintf("Search data Done, Data:%d Index:%d", data, index))
			return
		} else {
			index++
			point = point.Next
			if index > GetListLength(head) - 1 {
				fmt.Println(fmt.Sprintf("Data %d not exist", data))
				break
			}
		}
	}
	return
}

//根据Index获取元素的值
func GetData(head *ListNode, index int) (data Element) {
	if index < 0 ||  index > GetListLength(head) {
		fmt.Println("Index error,Please check again.")
		return
	}

	point := head
	for i := 0; i < index; i++ {
		point = point.Next
	}
	data = point.Data
	fmt.Println(fmt.Sprintf("Index:%d Data:%d", index, data))
	return
}

func (head *ListNode) PrintList() {
	point := head
	if point == nil {
		fmt.Println("List is nil, return!")
		return
	}
	for point.Next != nil {
		fmt.Print(fmt.Sprintf(" %d ",point.Data))
		point = point.Next
	}
	fmt.Println()
}

func GetListLength(head *ListNode) (length int) {
	point := head
	for point.Next != nil {
		length++
		point = point.Next
	}
	return
}

func ListInstance()  {
	Head := newHeader()
	if Head == nil {
		fmt.Println("Head is nil, return.")
	}

	for i := 1; i < 10; i++ {
		TailAdd(Head, Element(i))
	}
	Head.PrintList()

	HeadAdd(Head,1000)
	HeadAdd(Head,2000)
	HeadAdd(Head,3000)
	Head.PrintList()

	Delete(Head,2)
	Head.PrintList()

	Insert(Head,2, 101)
	Head.PrintList()

	Search(Head,101)
	GetData(Head,4)

}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值