237. Delete Node in a Linked List

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.

题目大意:删除给定节点,只给定相应的节点的访问权限

/**
 * 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 = *node->next;

        /*删除节点
         * auto next = node->next;
         * node = *next;
         delete next;
         */
    }
};

仔细思考了一下上面的代码,发现有很多bug,上面的代码只适用于要删除的节点不是尾节点的情况,没有考虑到下面的两种特例

(1)删除的节点是头结点也是尾节点(链表中只有一个节点)
(2)删除的节点是
void deleteNode(ListNode **pHead, ListNode *node){
  if(*pHead == NULL || node == NULL)return;

  //删除的节点不是尾节点
  if(node->next != NULL){
    ListNode *pNext = node->next;

    node->val = pNext->val;
    node->next = pNext->next;

    delete pNext;
    pNext = NULL;
  }
  //删除的节点所在链表只有一个节点,这个条件说明的是(删除的节点既是尾节点又是头结点)
  else if(*pHead == node){
    delete node;
    node = NULL;

    *pHead = NULL;
  }
  //删除的节点是尾节点
  else{
    ListNode *prev = *pHead;

    while(prev->next != node){
      prev = prev->next;
    }

    prev->next = NULL;
    delete node;
    node = NULL;
  }
}

results matching ""

    No results matching ""