新增一個給定的連結串列中的第一個節點的 Go 語言程式。
示例
解決此問題的步驟
步驟 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 AddFirstNode(head *Node, data int) *Node{ if head == nil{ head = NewNode(data, nil) return head } newNode := NewNode(data, nil) newNode.next = head return newNode } func main(){ head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil)))) fmt.Printf("Input Linked list is: ") TraverseLinkedList(head) head = AddFirstNode(head, 5) fmt.Printf("After adding first node, linked list is: ") TraverseLinkedList(head) }
輸出
Input Linked list is: 30 10 40 40 After adding first node, linked list is: 5 30 10 40 40
廣告