O (1) time to delete a linked list node

Source: Internet
Author: User

Problem Description: the head pointer and a node pointer to the order-linked list, defining a function to delete the node at O (1) time.

This is relatively simple, do not explain, directly read the reference code, but one thing is to note, or to see the deleted node type, can not guarantee always O (1) time

Reference code:

void Deletenode (listnode** phead,listnode *ptobedelete)
{
if ((Phead = = NULL) | | (*phead = = NULL) | | (Ptobedelete = = NULL))
{
Return
}

The node in the middle of the linked list is deleted
if (ptobedelete->m_pnext! = NULL)
{
ListNode *pnode = ptobedelete->m_pnext;
Ptobedelete->m_nvalue = pnode->m_nvalue;
Ptobedelete->m_pnext = pnode->m_pnext;
Delete Pnode;
Pnode = NULL;
}
Else
{//Only one node
if (Ptobedelete = = *phead)
{
Delete *phead;
Phead = NULL;
Ptobedelete = NULL;
}
Else
{//Deleted tail node
ListNode *pnode = *phead;
while (pnode->m_pnext! = ptobedelete)
{
Pnode = pnode->m_pnext;
}
Pnode->m_pnext = NULL;
Delete Ptobedelete;
Ptobedelete = NULL;
}
}
}

O (1) time to delete a linked list node

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.