Delete a linked list node at O (1) time

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.