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ǔ)概念