LeetCode - 237. Delete Node in a Linked List #Java

Question

刪除單鏈表中的節(jié)點

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;  // 節(jié)點的值
      ListNode next; // 節(jié)點的指針
      ListNode(int x) { val = x; }
  }

Solutions

這里要注意不僅要替換鏈表的指針,值也要換,一開始就只換了指針忘記換值了。

public class Solution {
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

Points

  • 是否對節(jié)點為null時進行處理
    不太懂為何node.next = node.next.next;這里不判斷下

TO DO

  • 鏈表的基礎(chǔ)概念
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容