Go语言双向链表尾节点插入后反向遍历异常问题排查
问题排查与修复
你的双向链表反向遍历看不到新插入的"Pink",核心问题是插入新节点后没有更新链表的tail指针。
问题分析
在insertLast的else分支中,你完成了当前尾节点next指向新节点、新节点prev指向当前尾节点、新节点next置为nil这三个操作,但链表结构体list中的tail字段始终停留在原来的尾节点(即"Arjun")。反向遍历是从tail指针开始的,自然无法找到新插入的"Pink"节点。
修复代码
修改insertLast的else分支,最后添加更新tail指针的语句即可:
func (listReceiver *list) insertLast(incomingValue string) { printNewLine := fmt.Println newNode := node{value: incomingValue} currentNode := listReceiver.head if listReceiver.head == nil { listReceiver.head = &newNode listReceiver.tail = &newNode fmt.Printf("New head -- %s", listReceiver.head.value) printNewLine() listReceiver.length++ } else { for currentNode.next != nil { printNewLine(currentNode.value) currentNode = currentNode.next } currentNode.next = &newNode newNode.next = nil newNode.prev = currentNode // 新增:将链表的tail指针更新为新节点 listReceiver.tail = &newNode fmt.Printf("New Tail -- %s ", newNode.value) printNewLine() listReceiver.length++ } }
额外优化建议
其实你不需要从头遍历到尾找当前尾节点,链表已经维护了tail字段,直接复用它可以省去循环,大幅提升插入效率:
func (listReceiver *list) insertLast(incomingValue string) { printNewLine := fmt.Println newNode := node{value: incomingValue, next: nil} if listReceiver.head == nil { listReceiver.head = &newNode listReceiver.tail = &newNode fmt.Printf("New head -- %s", listReceiver.head.value) printNewLine() } else { newNode.prev = listReceiver.tail listReceiver.tail.next = &newNode listReceiver.tail = &newNode fmt.Printf("New Tail -- %s ", newNode.value) printNewLine() } listReceiver.length++ }
内容的提问来源于stack exchange,提问作者Arjun Malhotra
相关产品推荐
相关产品推荐

