leetcode solution to a problem --237, delete the list of nodes

Please write a function that makes it possible to delete a list given (non-end) node, you will only be required for a given node is removed.

A list of existing - head = [4,5,1,9], it can be expressed as:

spacer.gif

Example 1:

Input: head = [4,5,1,9], node = 5

Output: [4,1,9]

Explanation: You list whose value is given the second node 5, then after your function call, the list strain 4 -> 1 -> 9.

Example 2:

Input: head = [4,5,1,9], node = 1

Output: [4,5,9]

Explanation: After a given you third node list whose value is 1, then your function call, the list strain 4 -> 5 -> 9.



Problem-solving ideas:

        Speaking of the title, only to be given to the node requested to be removed, therefore, no need to consider traverse the entire node, a node only need to delete the current

C++

/**
* 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) {
        node->val = node->next->val;
        ListNode* toDel = node->next;
        node->next = toDel->next;
        delete toDel;
        toDel = NULL;
    }
};


Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        node.val = node.next.val
        node.next = node.next.next








Guess you like

Origin blog.51cto.com/12876518/2407070