Question
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.
題目
給定一個(gè)單鏈表中的一個(gè)等待被刪除的節(jié)點(diǎn)(非表頭或表尾)。請(qǐng)?jiān)谠贠(1)時(shí)間復(fù)雜度刪除該鏈表節(jié)點(diǎn)。
樣例
給定1->2->3->4,和節(jié)點(diǎn)3,刪除 3 之后,鏈表應(yīng)該變?yōu)?->2->4。
分析
一般,刪除鏈表節(jié)點(diǎn)需要前置節(jié)點(diǎn),需要n的時(shí)間復(fù)雜度。但這里要實(shí)現(xiàn)1的復(fù)雜度。
看似很難,無法解決。其實(shí)很簡單,我們轉(zhuǎn)換思路,我們可以刪除當(dāng)前的節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn),那么我們就刪除下一個(gè)節(jié)點(diǎn),不過,在刪除之前,把下一個(gè)節(jié)點(diǎn)的值保存到當(dāng)前節(jié)點(diǎn)就可以了,這樣不久相當(dāng)于刪除了當(dāng)前節(jié)點(diǎn)么?當(dāng)然當(dāng)頭尾節(jié)點(diǎn)這樣就行不通了。
代碼
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param node: the node in the list should be deleted
* @return: nothing
*/
public void deleteNode(ListNode node) {
// write your code here
node.val = node.next.val;
node.next = node.next.next;
}
}