Go 語言程式在給定連結串列末尾新增一個節點。


示例


下一步

5

解決此問題的辦法

步驟 1 − 定義一個方法,該方法接受連結串列的頭。

步驟 2 − 如果頭 == 無,建立一個新節點並返回該節點。

步驟 3 − 如果頭不為無,則一直向後遍歷到連結串列的倒數第二個。

示例

 即時演示

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("Input Linked list is: ")
   TraverseLinkedList(head)
   AddNodeAtEnd(head, 5)
   fmt.Printf("After adding node at end, linked list is: ")
   TraverseLinkedList(head)
}

輸出

Input Linked list is: 30 10 40 40
After adding node at end, linked list is: 30 10 40 40 5

更新於: 18-3-2021

494 次瀏覽

開啟你的職業生涯

完成該課程即可獲得認證

開始學習
廣告
© . All rights reserved.