添加一个给定的链表中的第一个节点的 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP