Golang 程序在给定的链接列表末尾添加一个节点。

go programmingserver side programmingprogramming

示例

下一步

5
Null

解决此问题的方法问题

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

步骤 2 − 如果 head == nil,则创建一个新节点并返回该节点。

步骤 3 − 如果 head 不为 nil,则遍历到链接列表的倒数第二个。

示例

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 AddNodeAtEnd(head *Node, data int) *Node{
   if head == nil{
      head = NewNode(data, nil)
      return head
   }
   temp := head
   for temp.next != nil {
      temp = temp.next
   }
   temp.next = NewNode(5, nil)
   return head
}
func main(){
   head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil))))
   fmt.Printf("输入链表为:")
   TraverseLinkedList(head)
   AddNodeAtEnd(head, 5)
   fmt.Printf("在末尾添加节点后,链表为:")
   TraverseLinkedList(head)
}

输出

输入链表为:30 10 40 40
在末尾添加节点后,链表为:30 10 40 40 5

相关文章