LeetCode---List 1

1. Topic

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.


2. Answer: The difficulty of this question is that the previous node of the node cannot be found, so it cannot be done by conventional methods. So use the "replace" method to solve.

 

3. Code C++

 

class Solution {
public:
    void deleteNode(ListNode* node) {
        ListNode *p;            
        p = node->next; //Save the next node of the node node to release the node
        node->val = node->next->val;
        node->next = node->next->next;
        free(p);
    }
};


 code python

class Solution(object):
    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 http://43.154.161.224:23101/article/api/json?id=325636039&siteId=291194637