剑指offer13 在O(1)时间删除链表的结点
把下一个节点的值直接赋值给要删除的节点,然后删除下一个节点。当这样做会有两个bad case:被删除的链表结点的下一个结点为空指针,如果链表只有一个结点。其实链表只有一个结点应该属于下一个结点为空指针的大类,但处理方式不同。整个方案就是下一个结点是否是空指针
void deleteNode(TreeNode* pListHead,TreeNode* pToBeDeleted){ if(pListHead == NULL || pToBeDeleted == NULL) return; if(pToBeDeleted->next != NULL){ TreeNode* pnext == pToBeDeleted->next; pToBeDeleted->val = pnext->val; pToBeDeleted->next = pnext->next; delete pnext; pnext = NULL; } else if(pListHead == pToBeDeleted){ pListHead == NULL; delete pToBeDeleted; pToBeDeleted == NULL; } else{ TreeNode* pNode = pListHead; while(pNode->next != pToBeDeleted){ pNode = pNode->next; } pNode->next == NULL; delete pToBeDeleted; pToBeDeleted == NULL; } return; }