go语言编写linktable库

你不定积分没加C 2022-04-06 14:59:34

1、定义结点及链表数据结构

type Node struct{
	Value int
	Next *Node
}

type List struct {
	Length int
	Head *Node
}

2、初始化链表

func Init()List{
	var list List
	list.Head=nil
	list.Length=0
	return list
}

3、在location位置添加值为value的结点

func Insert(list *List,value int,location int)bool{
	if location<0||location>list.Length{
		return false
	}
	var node=new(Node)
	node.Value=value
	if location==0{
		node.Next=list.Head
		list.Head=node
		list.Length++
		return true
	}
	var p=list.Head
	for i:=1;i<location;i++{
		p=p.Next
	}
	node.Next=p.Next
	p.Next=node
	list.Length++
	return true
}

4、删除location位置的结点

func Delete(list *List,location int)bool{
	if location<0||location>list.Length{
		return false
	}
	if location==0 {
		list.Length--
		list.Head=list.Head.Next
		return true
	}
	var node=list.Head
	for i:=1;i<location;i++{
		node=node.Next
	}
	if node.Next.Next==nil{
		node.Next=nil
	}else {
		node.Next=node.Next.Next
	}
	list.Length--
	return true
}

5、返回值为value的结点

func Search(list *List,value int)*Node{
   var node=list.Head
   for i:=0;i<list.Length;i++{
      if node.Value==value{
         return node
      }
      node=node.Next
   }
   return nil
}

6、代码地址

地址

 学号:412

...全文
90 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

571

社区成员

发帖
与我相关
我的任务
社区描述
软件工程教学新范式,强化专项技能训练+基于项目的学习PBL。Git仓库:https://gitee.com/mengning997/se
软件工程 高校
社区管理员
  • 码农孟宁
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧