The method of deleting linked list nodes in Go language: first move the value of the next node to the currently deleted node; then change the Next of the current node, such as [node.Next = node.Next.Next].
#The operating environment of this article: windows10 system, GO 1.11.2, thinkpad t480 computer.
Specific method:
Optimal solution:
Move the value of the next node to the current deleted node, and then change the Next
node.Val = node.Next.Val node.Next = node.Next.Next
of the current node Other methods:
p.next = p.next.next can achieve the purpose of deletion
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func deleteNode(head *ListNode, val int) *ListNode { if head.Val == val{ return head.Next } pre:=head for head.Next.Val != val{ head = head.Next } head.Next = head.Next.Next return pre }
Title:
Delete the node in the linked list
Please write a function so that it can delete a given (non-end) node in a linked list, you will only be given the node requested to be deleted.
There is an existing linked list – head = [4,5,1,9], which can be expressed as:
Example 1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: Given the second node with value 5 in your linked list, Then after calling your function, the linked list should become 4 -> 1 -> 9.
Example 2:
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: Given the third node with a value of 1 in your linked list, then after calling your function, the linked list should become 4 -> 5 -> 9.
Code
Still pay attention to achieve the purpose of deletion
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func deleteNode(node *ListNode) { for node.Next.Next != nil { node.Val = node.Next.Val node = node.Next } node.Val = node.Next.Val node.Next = nil }
Related recommendations: golang tutorial
The above is the detailed content of How to delete linked list nodes in go language. For more information, please follow other related articles on the PHP Chinese website!