题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
package main import ( "fmt" ) // type ListNode struct { // Val int // Next *ListNode // } func createLinkList(headNodeValue int, pairs [][]int) *ListNode { dummy := ListNode{} dummy.Next = &ListNode{Val: headNodeValue, Next: nil} prev := &dummy for _, pair := range pairs { p := prev.Next for p != nil { if p.Val == pair[1] { node := ListNode{Val: pair[0], Next: p.Next} p.Next = &node break } p = p.Next } } return dummy.Next } func removeElement(head *ListNode, k int) *ListNode { dummy := ListNode{} dummy.Next = head p := &dummy for p != nil { if p.Next.Val == k { p.Next = p.Next.Next return dummy.Next } p = p.Next } return dummy.Next } func main() { var n int var headNodeVal int fmt.Scan(&n, &headNodeVal) var pairs [][]int for i:=0; i<n-1; i++ { var val1, val2 int fmt.Scan(&val1, &val2) pairs = append(pairs, []int{val1, val2}) } var k int fmt.Scan(&k) head := createLinkList(headNodeVal, pairs) head = removeElement(head, k) for head != nil { fmt.Printf("%d ", head.Val) head = head.Next } }
// 本题输入一行数字,分别代表不同含义,所以采用:fmt.Scan(&val1, &val2)