237. Delete Node in a Linked List

来源:互联网 发布:格雷格.门罗数据 编辑:程序博客网 时间:2024/06/05 21:49

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);

}