current position：Home>[algorithm learning] 02.03 Delete intermediate nodes (Java / C / C + + / Python / go)
[algorithm learning] 02.03 Delete intermediate nodes (Java / C / C + + / Python / go)
2022-01-30 02:00:54  ~
02.03. Delete intermediate nodes ：
If a node in the linked list , Not a chain header node , Nor is it the tail node of the list , It is called the of the linked list 「 Intermediate nodes 」.
Suppose you know an intermediate node of the linked list , Please implement an algorithm , Delete the node from the linked list .
for example , Incoming node c（ Located in one-way linked list a->b->c->d->e->f in ）, After deleting it , The remaining linked list is a->b->d->e->f
Examples 1
Input ： node 5 （ Located in one-way linked list 4->5->1->9 in ） Output ： No data is returned , Delete the incoming node from the linked list 5, Make the linked list 4->1->9 Copy code
analysis
- The address of the next node is stored in the previous node of the linked list , General delete node , Is to directly connect the previous node of the current node with the next node of the current node .
- This question only passes in the node to be deleted , Therefore, the address of the current node cannot be changed , You can only change the value . From a business perspective , Don't care about the address of the linked list , What I care about is the value inside , So let's just make the value look deleted , Even if the current node is deleted .
- This question is officially not allowed to be chosen rust, The second leader had to give up .
Answer key
java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public void deleteNode(ListNode node) { node.val = node.next.val; node.next = node.next.next; } } Copy code
c
/** * 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; } Copy code
c++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void deleteNode(ListNode* node) { node->val = node->next->val; node->next = node->next->next; } }; Copy code
python
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = node.next.val node.next = node.next.next Copy code
go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func deleteNode(node *ListNode) { node.Val = node.Next.Val node.Next = node.Next.Next } Copy code
Original title transmission gate ：
author[White hat of the second leader]