Golang 程序从链接列表中删除第一个节点。
go programmingserver side programmingprogramming
示例
解决此问题的方法
步骤 1 − 定义一个接受链接列表头部的方法。
步骤 2 − 如果 head == nil,则返回头部。
步骤 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 DeleteFirstNode(head *Node) *Node{ if head == nil{ return head } newHead := head.next head.next = nil return newHead } func main(){ head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil)))) fmt.Printf("输入链表为:") TraverseLinkedList(head) head = DeleteFirstNode(head) fmt.Printf("删除链表第一个节点后:") TraverseLinkedList(head) }
输出
输入链表为:30 10 40 40 删除链表第一个节点后:10 40 40