Want to delete node, but not preve node, so copy the next to node, then delete the node->next.


  • 0
    M

    /**

    • 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) {
      // want to delete node, but not preve node, so copy
      // the next to node, then delete the node->next.
      if (node->next) {
      ListNode* p=node->next;
      node->val=p->val;
      node->next=p->next;
      delete p;
      } else {
      ListNode *p = node;
      node = NULL;
      delete p;
      }
      }
      };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.