Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4
and you are given the third node with value 3
,
the linked list should become 1 -> 2 -> 4
after calling your function.
題意:寫一個函數來刪除一個單鏈表中的一個節點(除了尾部),只訪問該節點。就是在不知道頭指針的情況下刪除指定節點
思路:讓指定節點的值等於它的下一個節點的值;然後將該指定節點的指針指向它的下下個節點。
**
* 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) {
if (node == null || node.next == null) {
return;
}
node.val = node.next.val;
node.next = node.next.next;
}
}