算法
Java
Leetcode
Delete a node in a singly linked list.
Question
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
See it on Leetcode
1 2 3
| Supposed the linked list is 1 -> 2 -> 3 -> 4, and you are given the third node with value 3, it should become 1 -> 2 -> 4.
|
Hint
- The given node could be any node except the tail.
- You’re given only access to that node.
Solution in Java, C++ and Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public void deleteNode(ListNode node) { node.val = node.next.val; node.next = node.next.next; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| * 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; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
class Solution(object): 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
|