Title: The head pointer and a node pointer to the Order Necklace table, defining a function to delete the node at O (1) time.
Analytical:
Deleting a node in a one-way list is a common practice where the previous node of the node to be deleted must be found to be implemented, and the time complexity of doing so is O (n), which does not meet the requirements.
Innovative ideas: when we want to delete a node, it is not necessary to delete the node itself, you can use the current node to save its next node value, and then delete its next node.
Case study:
1. Input node is null
2. Single-linked list only one node, that is, delete the head node
3. The node to be deleted is the tail node, that is, there is no next node
4. Pending deletion is not a tail node
When the node to be deleted is a tail node, the usual method is to find the previous node of the node to be deleted to achieve O (n), but for other non-tailed nodes can be deleted at O (1) time, so the average time complexity is [(n-1) *o (1) + O (n)]/n, the result is O (1)
Comment:
When you delete a node, you do not have to delete the node itself, you can delete its next
Delete a node, either free or delete, and set to null
typedef struct LISTNODE {int val; struct ListNode*Next;} ListNode;//If you want to find the first node to be deleted is O (n),//To achieve O (1) cannot be found, so we use to delete the node to save its next node's content, and then delete the next nodeListNode*Deleteelement (ListNode*Head, ListNode*ptodeleted) {if(Head== NULL ||ptodeleted== NULL)returnHead//Only one node if(Head==ptodeleted) {Delete ptodeleted; Head= NULL; ptodeleted= NULL;return NULL; }if(ptodeleted -Next== NULL) {//To be deleted as the last nodeListNode*Pnode=Head while(Pnode -Next!=ptodeleted)//General method to find the previous node to be deleted.Pnode=Pnode -Next Pnode -Next= NULL; Delete ptodeleted; ptodeleted= NULL; }Else{//The node to be deleted is not a tail nodeListNode*Pnext=ptodeleted -Next ptodeleted -Val=Pnext -Val ptodeleted -Next=Pnext -Next Delete Pnext; Pnext= NULL; }returnHead;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
13: Delete single-linked list node at O (1) time