Golang 程序从链表中删除第一个节点。
示例
解决此问题的办法
步骤 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 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("Input Linked list is: ") TraverseLinkedList(head) head = DeleteFirstNode(head) fmt.Printf("After deleting first node of the linked list: ") TraverseLinkedList(head) }
输出
Input Linked list is: 30 10 40 40 After deleting first node of the linked list: 10 40 40
广告