Leetcode ☞237. Delete Node in a Linked List ☆

237. Delete Node in a Linked List

My Submissions
Question
Total Accepted: 65936  Total Submissions: 150816  Difficulty: Easy

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.








我的AC(4ms,前98%):

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
void deleteNode(struct ListNode* node) {
    struct ListNode *p;
    
    p = node->next;
    node->val =  p->val;
    node->next = p->next;
    
    free(p);
}


分析:

认真读题。提供的是所要删除的那个节点!!!没给各个节点的值也没给长度


所以把该node的所有“属性”都改成“node->next”的属性,这时原node其实就已经没了(有两个node->next)!然后free掉node->next。

链表的题,画图后就很容易理解。


举个例子:

a->b->c->d->e->····->z,要删c。

那我们其实不是真删了c,(实际是删了c->next)。我们把d的val跟d->next都给c,原链表就变成了

a->b->d(本来是C,值改成了d)->e->····->z 和 d->e->····->z。 然后free掉这个枝杈d。


你可能感兴趣的:(Leetcode,C/C艹)