Golang 程序更新链接列表中的最后一个节点值。

go programmingserver side programmingprogramming

示例

解决此问题的方法

步骤 1 − 定义一个接受链接列表头部的方法。

步骤 2 − 如果 head == nil,则返回头部。

步骤 3 − 否则,将最后一个节点值更新为 41。

示例

package main
import "fmt"
type Node struct {
   value int
   next *Node
}
func NewNode(value int, next *Node) *Node{
   var n Node
   n.value = value
   n.next = next
   return &n
}
func TraverseLinkedList(head *Node){
   temp := head
   for temp != nil {
      fmt.Printf("%d ", temp.value)
      temp = temp.next
   }
   fmt.Println()
}
func UpdateLastNodeValue(head *Node, data int) *Node{
   if head == nil{
      return head
   }
   temp := head
   for temp.next != nil{
      temp = temp.next
   }
   temp.value = data
   return head
}
func main(){
   head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil))))
   fmt.Printf("输入链表为:")
   TraverseLinkedList(head)
   head = UpdateLastNodeValue(head, 41)
   fmt.Printf("更新最后一个节点值后,链表为:")
   TraverseLinkedList(head)
}

输出

输入链表为:30 10 40 40
更新最后一个节点值后,链表为:30 10 40 41

相关文章