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

SYN_1 SYN_1 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区

代码

// 定义结点
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

...全文

相关推荐

评论
收藏 已收藏
分享
返回顶部