題目描述
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.
代碼實(shí)現(xiàn)
/**
* 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) {
//先讓該結(jié)點(diǎn)的值等于下一個(gè)結(jié)點(diǎn)的值12345->12445
node.val = node.next.val;
//再把下一個(gè)結(jié)點(diǎn)刪除12445->1245
node.next = node.next.next;
}
}
主要思路
很簡(jiǎn)單,只需要把當(dāng)前結(jié)點(diǎn)的值復(fù)制為下一個(gè)結(jié)點(diǎn)的值,然后刪除下一個(gè)結(jié)點(diǎn),就相當(dāng)于把當(dāng)前結(jié)點(diǎn)刪除了