用Go编写一个Linktable库,并上传到github

SYN_1 2022-07-10 20:13:56

代码

// 定义结点
type Node struct {
	val  int
	next *Node
}
 
// 定义链表
type LinkedList struct {
	dummy *Node
}
 
// 初始化链表
func Constructor() LinkedList {
    return LinkedList {
		&Node{},
	}
}
 
// 获取index位置节点
func (this *LinkedList) Get(index int) int {
    if(index < 0) return -1
	head := this.dummy.next
	if head == nil return -1
	for head.next != nil && index > 0{
		head = head.next
		index--
	}
	return head.val
}
 
// 头插法
func (this *LinkedList) AddAtHead(val int)  {
	dummy := this.dummy
	node := &Node{
		val:  val,
		next: dummy.next,
	}
	this.dummy.next = node
}
 
// 尾插法
func (this *LinkedList) AddAtTail(val int)  {
	dummy := this.dummy
	for dummy.next != nil {
		dummy = dummy.next
	}
	rear := &Node{
		val: val,
		next: nil,
	}
	dummy.next = rear
}
 
// 在index位置插入节点
func (this *LinkedList) AddAtIndex(val int, index int)  {
    if(index < 0) return 
    dummy := this.dummy
	for dummy.next != nil && index > 0 {
		dummy = dummy.next
		index--
	}
	if index != 0 {
		return
	}
	node := &Node{
		val:  val,
	}
	node.next = dummy.next
	dummy.next = node
}
 
// 在index位置删除节点
func (this *LinkedList) DeleteAtIndex(index int)  {
    if(index < 0) return 
	if this.dummy.next == nil {
		return
	}
    dummy := this.dummy
	for dummy.next != nil && index > 0 {
		dummy = dummy.next
		index--
	}
	if dummy.next != nil && index == 0 {
		dummy.next = dummy.next.next
	}
}

测试结果

上传到远程仓库

 https://github.com/Y-SYN

 

学号:523

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

566

社区成员

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

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