237. 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 value3, 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) 
    {
        
    }
}

Solution:

咋一看這道題感覺就是最基本的鏈表操作,剛準備動手發(fā)現(xiàn)并不能訪問鏈表本身(并沒有給出鏈表的頭結點),又由于單鏈表沒有前向指針,所以不能用簡單的刪除節(jié)點的思路。

參考Discuss后得到思路:

  1. 判斷待刪除的node是否是最后一個node,如果是則直接將最后一個節(jié)點刪除(雖然該該題目指明不需要考慮鏈表中的最后一個節(jié)點,但考慮有最后一個節(jié)點的情況更為周全)。Java似乎無法實現(xiàn)刪除最后一個節(jié)點,無法將所有指向最后一個節(jié)點的引用置為null(一共有兩個引用指向最后一個節(jié)點,分別是該函數(shù)的參數(shù)node,和最后一個節(jié)點的前驅節(jié)點的next)。如果用C/C++則可以直接調用delete運算符。
  2. (如果不是最后一個節(jié)點)將后一個節(jié)點的val拷貝到當前節(jié)點val,然后刪除后一個節(jié)點(將當前節(jié)點的next指向null

code:

/**
 * 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.next == null)  // this part is useless according to the requirement and Java
            node = null;  // in C++ we can delete node;
        else
        {
            node.val = node.next.val;
            node.next = node.next.next;
        }
        
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容