// index是不能取到 this.Size这个数字的 // index最大能取到 this.Size-1 究其原因就是因为数量和索引的关系,索引第一个为0 // 下面两个等价,答案总是写第一个,我习惯第二个,所以一开始就把我限制了 if index >= this.Size{} if index > this.Size{} -------- //还有一种写法 if index > this.Size{} // 这种写法出现的时候你就要考虑一下节点是否能取到,this.Size这个节点了(本来是空) // 就像AddAtIndex中是可以在末尾取到的
我发现正确答案是多不喜欢写 this!=nil 别问我为什么,我也不知道,反正我写了
再其次
重申一下名字
1 2 3 4 5 6 7 8
MyLinkedList -- 链表 SingleList -- 单个节点 newCode -- 新建的节点 cur -- 一般是复制虚拟头结点的操作 this -- 就是一个对象 Size -- 链表大小 Val-- 节点数据 Index -- 索引
代码呈现
1 2 3 4 5 6 7 8
type SingleNode struct { Val int Next *SingleNode } type MyLinkList struct { dummyHead *SingleNode Size int }
// 获得第Index个节点的数据 func(this *MyLinkList) Get(index int) int { // 这里要判断三个条件, 不存在以及index无效的情况 if index < 0 || index > this.Size-1 || this == nil { return-1 } cur := this.dummyHead for i := 0; i <= index; i++ { cur = cur.Next } return cur.Val }
// 添加节点到尾部 func(this *MyLinkList) AddAtTail(val int) { newCode := &SingleNode{Val: val} cur := this.dummyHead for cur.Next != nil { cur = cur.Next } cur.Next = newCode this.Size++ }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//添加节点到 Index func(this *MyLinkList) AddAtIndex(index int, val int) { // 如果index=this.Size 则index刚刚好是最后一个节点的后面一个新建节点 if index > this.Size || index < 0 || this == nil { return } // 正确答案里 index<0时要变成index=0,我非常不理解 // 正确答案里没有this== nil // 我感觉我的答案就是对的 newCode := &SingleNode{Val: val} cur := this.dummyHead for i := 0; i < index; i++ { cur = cur.Next } newCode = cur.Next.Next cur.Next = newCode this.Size++ }
1 2 3 4 5 6 7 8 9 10 11 12
// 删除Index中的数据 func(this *MyLinkList) DeleteAtIndex(index int) { if index < 0 || index > this.Size-1 || this != nil { return } cur := this.dummyHead for i := 0; i < index; i++ { cur = cur.Next } cur.Next = cur.Next.Next this.Size-- }