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