Implement an algorithm to delete a node in the middle (i.e., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node.
Hint
- Picture the list 1-> 5 - >9 - > 12. Removing 9 would make it look like 1-> 5 - > 12. You only have access to the 9 node. Can you make it look like the correct answer?
Solution
本題要我們刪除鏈表內(nèi)除了首尾外的任意一個結(jié)點专普,條件只有要刪除的結(jié)點而沒有給出鏈表的頭結(jié)點,因此和以往的刪除操作處理略有不同茂翔。我們可以用這樣的思路分歇,使用當(dāng)前結(jié)點的下一個結(jié)點值覆蓋當(dāng)前結(jié)點歧匈,然后再刪除當(dāng)前結(jié)點的下一個結(jié)點即可。
public void deleteMiddleNode(ListNode node) {
if (node == null || node.next == null) return;
node.val = node.next.val;
node.next = node.next.next;
}