Delete linked list nodes and nodes in O (1) Time
Question: given a one-way linked list head pointer and a node pointer, define a function to delete the node at O (1) time.
Struct ListNode
{
Int m_nValue;
ListNode * m_pNext;
};
Void DeleteNode (ListNode ** pListHead, ListNode * pToBeDeleted );
Algorithm ideas:
Generally, we traverse from the first node. We know that we find the first node of the node to be deleted, but the time complexity is O (n)
Improvement idea: Find the next node pNext of the node pDeleteNode to be deleted, and set the value of the next node (pNext-> m_nValue)
Assign the node to be deleted (PDeleteNode-> m_nValue), and point the node to the next node of the next node: (pDelete-> m_pNext = pNext-> m_pNext)
Then delete the pNext node, pNext = NULL;
Code:
// DeleteNodeInList. cpp: defines the entry point of the console application. // # Include "stdafx. h "# include <iostream> using namespace std;/* algorithm idea: we generally traverse from the first node and find the first node to be deleted, however, the time complexity is O (n). Improvement: Find the next node pNext of the node pDeleteNode to be deleted, and set the value of the next node (pNext-> m_nValue) assign the node to be deleted (PDeleteNode-> m_nValue), and point the node to the next node of the next node: (pDelete-> m_pNext = pNext-> m_pNext) then delete the pNext node, pNext = NULL; */struct ListNode {int m_nValue; ListNode * m_pNext ;}; void DeleteNode (ListNode ** pListHead, ListNode * pToBeDeleted) {I F (! PListHead |! PToBeDeleted) {return;} if (pToBeDeleted-> m_pNext! = NULL) // The deleted node is not the tail node {ListNode * p = pToBeDeleted-> m_pNext; pToBeDeleted-> m_nValue = p-> m_nValue; pToBeDeleted-> m_pNext = p-> m_pNext; delete p; p = NULL;} else if (* pListHead = pToBeDeleted) // The linked list has only one node, delete the header node is also the tail node {delete pToBeDeleted; pToBeDeleted = NULL; * pListHead = NULL;} multiple nodes in the else // Linked List, delete the tail node {ListNode * pNode = * pListHead; while (pNode-> m_pNext! = PToBeDeleted) {pNode = pNode-> m_pNext;} pNode-> m_pNext = pToBeDeleted-> m_pNext; delete pToBeDeleted; pToBeDeleted = NULL;}/* analysis: for n-1 non-tail nodes, we can copy the memory of the next node at O (1) Time to overwrite the node to be deleted and delete the next node. For tail nodes, because sequential search is still required, the time complexity is O (n ). therefore, the total average time complexity is [(n-1) * O (1) + O (n)]/n, so the average time complexity is O (1 ); */int _ tmain (int argc, _ TCHAR * argv []) {return 0 ;}
For n-1 non-tail nodes, We can overwrite the memory replication of the next node at O (1) and delete the next node;
For tail nodes, the time complexity is O (n) Because sequential search is still required ). therefore, the average time complexity is [(n-1) * O (1) + O (n)]/n,
Therefore, the average time complexity is O (1 );