2015年8月7日 星期五

LEET code--Delete Node in a Linked List

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.

一開始只給你要刪除的node的pointer
所以要把該刪除的node內部值改成下一個的
 像這樣
    p = node->next;
    if (!p) return;
    node->val = p->val;
    node->next = p->next;
    free(p);
P=上面範例的4
所以把3的內容改成4
再把4刪除
這樣3就不見了

但是更好的寫法是
如果不在乎刪除空間:
*node = *(node->next);
//直接把pointer的值改成下一個
*node是取pointer內部儲存的記憶體空間
直接改成*(node->next) 就可以把3變成4 (直接改記憶體位置)
如果要刪除空間:
struct ListNode* tofree = node->next;
*node = *(node->next);
free(tofree);

沒有留言:

張貼留言