Title: The head pointer and a node pointer for the given unidirectional list, defining a function to delete the node within the O (1) time. The linked list nodes and functions are defined as follows:
struct listnode{int m_nvalue; Listnode* M_pnext;}; void Deletenode (listnode** plisthead,listnode* ptobedeleted);
Analysis: To delete the node I, I first copy the contents of the next node J to I, and then I pointer to the node J of the next node point. At this point, delete the node J, the effect is equivalent to the node I deleted.
Here are a few small questions: 1. If the node to be deleted is at the end of the list, then there is no next node, we can only traverse the list from the beginning and complete the deletion. 2. If there is only one node in the list, and we want to delete the head node of the linked list, we also place the drop node of the linked list null after the node is deleted. Here is the implementation code:
Void deletenode (listnode** plisthead,listnode* ptobedeleted) { if (! plisthead| |! ptobedeleted) return; if (ptobedeleted->m_pnext!=null) { ListNode* pNext=pToBeDeleted->m_pNext; Ptobedeleted->m_nvalue=pnext->m_nvalue; ptobedeleted-> m_pnext=pnext->m_pnext; delete pNext; pNext=NULL; } else if (*plisthead==ptobedeleted) { delete pToBeDeleted; ptobedeleted=null; *plisthead=null; } else { listnode* pnode=*plisthead; while (pNode- >m_pnext!=ptobedeleted) { pNode=pNode->m_pNext; } pnode- >m_pNext=NULL; delete pToBeDeleted; ptobedeleted=null: }}
This article from "Fairy Road thousands of dust Dream" blog, please be sure to keep this source http://secondscript.blog.51cto.com/9370042/1582956
Delete a linked list node at O (1) time