Delete node from a linked list

August 24, 2015

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

My first thought was:

class Solution {
public:
    void deleteNode(ListNode* node) {
        node->val = node->next->val;
        node->next = node->next->next;
    }
};

However, we can do this in a neatly way:

class Solution {
public:
    void deleteNode(ListNode* node) {
        *node = *node->next;
    }
};