https://leetcode.com/problems/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.
請你寫一個void delNode(ListNode* cur),把cur node刪掉(cur node不會是tail node)。 比如有一個link list是 1 -> 2 -> 3 -> 4, 當我呼叫完 delNode(node3的pointer)之後,list變成 1 -> 2 -> 4。
你不用回傳任何東西,把指定的node刪掉就好了
[思路]
這和一般的delete node from link list不同之處在於,一般會給你list head和target value
像這樣 delNode(ListNode* head, int target)
然後你寫個while loop去找到target node
接著把target node的previous node的next設為target node的next,然後刪掉target node
e.g.
list = 1 -> 2 -> 3 -> 4
delNode(head, 3)的作法是
while loop從頭掃描list,當搜尋到3的時候,把2的next指向4,然後把3刪掉
但這題並沒有給你list head,它只給你target node的pointer,所以你無法取得previous node,無法修改pre node的next。 以上例來說就是你沒辦法接觸到2, 所以根本無法修改2的next pointer。
因此這邊引進第二種delete node的方式,我稱之為"取代法":
把target node的next node的資料copy到target node上面,然後刪掉next node。
像間諜片一樣,A詐死後模仿了B的身分容貌,並且把B殺掉,以B的身分活著,外界看來B還活著而A死了。(這真是哲學的問題,這樣子A還真的算活著嗎,B又真的死了嗎?從社會的角度看,B這個身分才是真正長長久久活著不是嗎)
e.g.
list = 1 -> 2 -> 3 -> 4
delNode(head, 3)的作法是
把node 3的value修改為4,list變成1 -> 2 -> 4' -> 4
然後把node 4刪掉,1 -> 2 -> 4'
請你寫一個void delNode(ListNode* cur),把cur node刪掉(cur node不會是tail node)。 比如有一個link list是 1 -> 2 -> 3 -> 4, 當我呼叫完 delNode(node3的pointer)之後,list變成 1 -> 2 -> 4。
你不用回傳任何東西,把指定的node刪掉就好了
[思路]
這和一般的delete node from link list不同之處在於,一般會給你list head和target value
像這樣 delNode(ListNode* head, int target)
然後你寫個while loop去找到target node
接著把target node的previous node的next設為target node的next,然後刪掉target node
e.g.
list = 1 -> 2 -> 3 -> 4
delNode(head, 3)的作法是
while loop從頭掃描list,當搜尋到3的時候,把2的next指向4,然後把3刪掉
但這題並沒有給你list head,它只給你target node的pointer,所以你無法取得previous node,無法修改pre node的next。 以上例來說就是你沒辦法接觸到2, 所以根本無法修改2的next pointer。
因此這邊引進第二種delete node的方式,我稱之為"取代法":
把target node的next node的資料copy到target node上面,然後刪掉next node。
像間諜片一樣,A詐死後模仿了B的身分容貌,並且把B殺掉,以B的身分活著,外界看來B還活著而A死了。(這真是哲學的問題,這樣子A還真的算活著嗎,B又真的死了嗎?從社會的角度看,B這個身分才是真正長長久久活著不是嗎)
e.g.
list = 1 -> 2 -> 3 -> 4
delNode(head, 3)的作法是
把node 3的value修改為4,list變成1 -> 2 -> 4' -> 4
然後把node 4刪掉,1 -> 2 -> 4'
--------------
[Code]
class Solution {
public:
void deleteNode(ListNode* node) {
ListNode* next = node->next;
node->val = next->val;
node->next = next->next;
delete next;
}
};