Title: The head pointer and a node pointer for a given unidirectional list, defining 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:
In general, we are starting from the beginning of the node, we know to find the node to delete the previous node, but the time complexity of O (n)
Improved thinking: Find the next node pdeletenode the node you want to delete Pnext, the value of the next node (pnext->m_nvalue)
Assign to the node to be deleted (Pdeletenode->m_nvalue), and then point the node to be deleted 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: Generally we are starting from the beginning of the node traversal, know to find the node to delete the previous node, but the time complexity of O (n) Improved thinking: Find the next node of the node Pdeletenode to be deleted Pnext, assign the value of the next node (pnext->m_nvalue) to the node to be deleted (Pdeletenode->m_nvalue), Then point the node to be deleted to the next node of the next node: (Pdelete->m_pnext = pnext->m_pnext) and then delete the Pnext node, pnext = Null;*/struct listnode{int m_ Nvalue; Listnode* M_pnext;}; void Deletenode (listnode** plisthead, listnode* ptobedeleted) {if (!plisthead | |!ptobedeleted) {return;} if (ptobedeleted->m_pnext! = NULL)//Delete the 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)//linked list has only one node, the deletion head node is also the tail node {Delete ptobedeleted;ptobedeleted = Null;*plisthead = NULL;} else//linked list with multiple nodes, delete 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 overwrite the next node's memory copy at O (1) to the node to be deleted and delete the next node, and for the tail node, the time complexity is O (n) because the sequential lookup is still required. So 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 node to be deleted at O (1) and delete the next node;
For tail nodes, the time complexity is O (n) because the sequential lookup is still required. Therefore the total average time complexity is [(n-1) *o (1) +o (n)]/n,
So the average time complexity is O (1);
Delete a linked list node in O (1) time