算法 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

  1. The given node could be any node except the tail.
  2. You’re given only access to that node.

Solution in Java, C++ and Python

  • java
  • cpp
  • 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;
}
}