How to remove an element from a linked list in Go langu…

In Go language, we can use pointers to remove elements from a linked list. First, we need to define a struct for a linked list node, which includes a value and a pointer to the next node. Then, we can use pointers to traverse the linked list, find the node to be deleted, and update the pointer of the previous node to point to the next node of the one being deleted, effectively removing the node.

Below is an example code demonstrating how to remove an element from a linked list.

package main

import "fmt"

// 链表节点结构体
type ListNode struct {
    Val  int
    Next *ListNode
}

// 遍历链表打印所有节点的值
func printList(head *ListNode) {
    cur := head
    for cur != nil {
        fmt.Printf("%d ", cur.Val)
        cur = cur.Next
    }
    fmt.Println()
}

// 删除链表中的指定元素
func deleteNode(head *ListNode, val int) *ListNode {
    // 头节点特殊处理
    if head.Val == val {
        return head.Next
    }

    cur := head
    for cur.Next != nil {
        // 找到需要删除的节点
        if cur.Next.Val == val {
            cur.Next = cur.Next.Next
            return head
        }
        cur = cur.Next
    }

    return head
}

func main() {
    // 创建链表 1 -> 2 -> 3 -> 4 -> 5
    head := &ListNode{Val: 1}
    node2 := &ListNode{Val: 2}
    node3 := &ListNode{Val: 3}
    node4 := &ListNode{Val: 4}
    node5 := &ListNode{Val: 5}
    head.Next = node2
    node2.Next = node3
    node3.Next = node4
    node4.Next = node5

    // 删除链表中的元素 3
    head = deleteNode(head, 3)

    // 打印删除元素后的链表
    printList(head)
}

When running the above code, the output is: 1 2 4 5, which indicates that element 3 has been successfully deleted from the linked list.

bannerAds