Saturday, August 1, 2015

Leetcode 237: delete node in a linklist





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.

这个题目和remove node in the linklist类似,不同的地方在于,只需要delete掉那个给定的Node, 而且只给了那个node的pointer, 解这个问题只能去改变node的val 和 pointer来达到目的了。

class Solution {
public:
    void deleteNode(ListNode* node) {
        //sanity check
        if (node == NULL) return;
        //change the val of the node and change the pointer
        node->val = node->next->val;
        node->next = node->next->next;
    }
};

No comments:

Post a Comment