Delete a linked list node at O (1) time

Source: Internet
Author: User

  In the past, we need to traverse the entire list to find the previous node that needs to be deleted, so that we can manipulate the deletion method, which requires O (n) time complexity, but this requires us to do it at O (1) time. We can only think of other ways.

  algorithm idea: In fact, we don't need to know a node before deleting a node. It is our practice to assign the value of the node behind the delete node to the node to be deleted (that is, overwrite the value of the node to be deleted) and delete the node (delete) behind the node. We also need to check the location of the node to be deleted, specific problems specific analysis, to achieve comprehensive.

  Algorithm implementation:

1typedefstructlistnode{2     intdata;3     structListNode *Next;4 }listnode;5 6 voidDeletenode (ListNode **phead, ListNode *valueindex) {7     if(!phead | |!valueindex) {//input Failed8         return;9     }Ten      One     if(Valueindex->next! = NULL) {//In Case 1, if the node is not a tail node, we will need to delete the node behind the node to refer to the node assigned to it. And then delete the node behind him. AListNode *node = valueindex->Next;  -Valueindex->data = node->data; -Valueindex->next = node->Next; the          -         Deletenode; -node =NULL; -     } +     Else if(*phead = = ValueIndex) {//If there is only one node -         DeleteValueIndex; +*phead =NULL; AValueIndex =NULL; at     } -     Else{//if deleted as a node, traverse all nodes -ListNode *p = *Phead; -          while(P->next! =valueindex) { -p = p->Next; -         } in          -P->next =NULL; to         DeleteValueIndex; +ValueIndex =NULL; -     } the}

Resources:

"The sword means offer"

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.