go 数据结构之单链表

单向链表也叫单链表,是链表中最简单的一种形式,它的每个节点包含两个域,一个信息域(元素域)和一个链接域。这个链接指向链表中的下一个节点,而最后一个节点的链接域则指向一个空值。

 

 

  • 表元素域elem用来存放具体的数据。
  • 链接域next用来存放下一个节点的位置(python中的标识)
  • 变量p指向链表的头节点(首节点)的位置,从p出发能找到表中的任意节点。
package main

import (
	"fmt"
)

type Node struct {
	data interface{}
	next *Node
}

type singleLinked struct {
	head *Node
}

func (this *singleLinked) Empty() bool {
	if this.head == nil{
		return true
	}else {
		return false
	}
}

func (this *singleLinked) Length() int {
	cur := this.head  // 获取头结点游标
	count := 0
	for {
		if cur != nil {
			count ++
			cur = cur.next
		}else {
			break
		}

	}
	return count
}

func (this *singleLinked) Add(param interface{})  {
	// 链表头部插入
	node := &Node{data: param}
	//temp := this.head
	//node.next = temp
	//this.head = node
	node.next, this.head = this.head, node
}

func (this *singleLinked) Append(param interface{})  {
	// 链表尾部插入
	node := &Node{data: param}
	if this.Empty(){
		this.head = node
	}else {
		cur := this.head
		for {
			if cur.next != nil{
				cur = cur.next
			}else {
				cur.next = node
				break
			}
		}

	}
}

func (this *singleLinked) Insert(param interface{}, pos int) {
	// 指定位置插入
	if pos <= 0 {
		this.Add(param)
	}else if pos >= this.Length(){
		this.Append(param)
	}else {
		node := &Node{data: param}
		count := 0  // 标记位置
		pre := this.head  // 指向指定位置pos的前一个位置,即pos-1
		for count < (pos -1) {
				count++
				pre = pre.next
		}
		// 退出循环表示找到位置
		node.next = pre.next
		pre.next = node
	}
}

func (this *singleLinked) Remove(param interface{})  {
	// 删除指定元素
	cur := this.head
	if cur.data == param {
		// 删除头结点
		this.head = cur.next
	}
	for cur.next != nil{
		if cur.next.data != param{
			cur = cur.next
		}else {
			cur.next = cur.next.next
		}
	}
}

func (this *singleLinked) RemoveWithIndex(index int) {
	// 删除指定索引的数据
	cur := this.head
	if index <= 0{
		this.head = cur.next
	}else if index >this.Length(){
		fmt.Println("超出链表长度")
		return
	}else {
		count := 0  // 标记位置
		//pre := this.head  // 指向指定位置pos的前一个位置,即pos-1
		for count < (index -1) {
			count++
			cur = cur.next
		}
		// 退出循环表示找到位置
		cur.next = cur.next.next
	}
}

func (this *singleLinked) Travel() {
	if !this.Empty() {
		cur := this.head
		for {
			if cur != nil{
				fmt.Printf("%v  ", cur.data)
				cur = cur.next
				// 这两行代码不能换位置,否则panic
			}else {
				break
			}
		}
	}
}

func (this *singleLinked) Find(param interface{}) bool {
	cur := this.head
	for cur.next != nil{
		if cur.data == param{
			return true
		}else {
			cur = cur.next
		}
	}
	return false
}


func main() {
	singleLinked := singleLinked{}
	...

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值