LeetCode#237 Delete Node in a Linked List

key: Linked List
Runtime: 16 ms / beats 15.47%
No reference

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
class Solution {
public:
    void deleteNode(ListNode* node) {
        ListNode *p, *q;
        p = node;   q = node->next;
        while(q->next != NULL)
        {
            p->val = q->val;
            p = q;
            q = q->next;
        }
        p->val = q->val;
        p->next = NULL;
    }
};

Update: instead node with the next address
Runtime: 16 ms / beats 15.47%
Reference:discuss

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
class Solution {
public:
    void deleteNode(ListNode* node) {
        auto next = node->next;
        *node = *(node->next);
        delete next;
    }
};

你可能感兴趣的:(LeetCode#237 Delete Node in a Linked List)