Delete the access to a single node in the programmer interview template.
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Question link: http://www.nowcoder.com/practice/75e0235da04141d4823eb74018e9e0bc? Rp = 1 & ru =/ta/cracking-the-coding-interview & qru =/ta/cracking-the-coding-interview/question-ranking
Description
Implement an algorithm to delete a node in the middle of a one-way linked list. Assume that you can only access this node.
If a node with deletion is specified, perform the delete operation. If the node is the end node, false is returned; otherwise, true is returned.
Ideas
How can we delete a node that cannot be found at the previous node? We can change our thinking. First, we can assign the next node to this node, which is equivalent to deleting this node, but at this time there are duplicate nodes in the linked list, we just need to point the next of the node to the next of the original node to complete the deletion operation.
/*struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {}};*/class Remove{public:bool removeNode(ListNode* pNode){// write code hereif(pNode==nullptr || pNode->next==nullptr)return false;ListNode *pNext = pNode->next;pNode->val = pNext->val;pNode->next = pNext->next;return true;}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source