刪除單向鏈表中的某個節點

題目:Delete Node in a linked List

描述:

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)
            return;
        ListNode nextNode = node.next;
        if (nextNode == null)
            return;
        node.next = nextNode.next;
        node.val = nextNode.val;
    }
}

算法解釋:

因爲沒有當前傳入節點的上一個節點,因此,需要想一個折中的辦法,由於上一個節點知道它的下一個節點就是當前傳入的節點,因此我們將當前節點中的所有信息換成當前節點的下一個節點的信息,也就變相的完成了節點的刪除。

發佈了54 篇原創文章 · 獲贊 16 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章