Skip to content

Latest commit

 

History

History
45 lines (32 loc) · 1.38 KB

237md.md

File metadata and controls

45 lines (32 loc) · 1.38 KB

LeetCode 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 value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

##翻譯 刪除連結串列的一個節點。

範例:
連結陣列1 -> 2 -> 3 -> 4 ,傳入3,則執行後連節陣列變成1 -> 2 -> 4

##思路 連結陣列每個節點(Node)有兩個屬性,值(val)與下一個節點(next),刪除節點其實就是讓連結的val與next。都跳過當前節點指向下一個節點。

其實這題沒很好,可以跳過,沒有顯示出連結陣列的特性,203. Remove Linked List Elements會比較完整的使用到連結陣列的特性。

##解題

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} node
 * @return {void} Do not return anything, modify node in-place instead.
 */
var deleteNode = function(node) {
    node.val = node.next.val;
    node.next = node.next.next;
};

以上程式碼用圖解釋,一開始的連結如上圖,將val:3節點的值用val:4取代,並將node.next指向val:5節點,本來val:4的記憶體空間就會被釋放出來