"Leetcode" 237. Delete the node in the linked list

Title description

Please write a function to delete a given (non-end) node in a linked list, and you will only be given the node that is required to be deleted.
There is a linked list – head = [4,5,1,9], which can be expressed as:
Insert picture description here
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 be 4 -> 1 -> 9.

Example 2:

Input: head = [4,5,1,9], node = 1
Output: [4,5,9] Explanation: Given
the third node whose value is 1 in your linked list , then after calling your function , The linked list should be 4 -> 5 -> 9.

Description:

The linked list contains at least two nodes.
The values ​​of all nodes in the linked list are unique.
The given node is not the end node and must be a valid node in the linked list.
Don't return any results from your function.

Language : C language
thinking analysis

  • Note that only the nodes that need to be deleted in the title, that is, the head will not be given when passing parameters
  • Don't be hindered by directional thinking. If you follow directional thinking, you will definitely think about how to find the previous node of the node that needs to be deleted, let the pointer field of the previous node point to the next node that needs to be deleted, and then delete the node
  • The real idea is very simple, two lines of code can be done. Simply put, let the next node of the node that needs to be deleted cover itself, and then point to the next node.

Code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

void deleteNode(struct ListNode* node) {
    node->val=node->next->val;
    node->next=node->next->next;
}

operation result
Insert picture description here

Guess you like

Origin blog.csdn.net/NanlinW/article/details/104784722