237. Delete Node in a Linked List

Writea function to delete a node (except the tail) in a singly linked list, givenonly access to that node.


Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given thethird node with value 3, the linked list should become 1 -> 2 -> 4 aftercalling your function.



 


 

這個問題要刪除一個結點,不過和普通有點不同,不知道頭結點,知道的是指向要刪除的結點的指針,

解決方案是,把下一個結點的值覆蓋了這個結點,然後把下一個結點刪除.代碼如下:


 

/**

 * Definition forsingly-linked list.

 * struct ListNode {

 *     intval;

 *    struct ListNode *next;

 * };

 */

void deleteNode(structListNode* node) {

    struct ListNode*p = node->next;

    node ->val=p->val;

    node ->next =p->next;

    free(p);

}


  


發佈了39 篇原創文章 · 獲贊 10 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章