Question: Given the head pointer and a node pointer of a singly linked list, define a function to delete the node in O(1) time
Ideas:
1. The most common practice is to start from the head node of the linked list, traverse sequentially to find the node to be deleted, and delete the node in the linked list, the time complexity is O(n).
2. To delete node i, first copy the content of the next node j of i to i, and then point the pointer of i to the next node of node j, and then delete node j. For n-1 non-tail nodes, the content of the next node can be copied to cover the node to be deleted in O(1) time, and then the next node is deleted; for the tail node, it is still necessary to search sequentially, and the time complexity is O(n), so the average is [(n-1)*O(1)+O(n)]/n, and the result is still O(1)
Note: It is assumed that the node to be deleted exists in the linked list
public class wr13deleteNode { // Method 1, sequential search public boolean deleteNode(ListNode head,int index){ if(index<1||index>length(head)){ return false; } if(index==1){ head=head.next; return true; } int i=2; ListNode preNode=head; ListNode curNode=preNode.next; while(curNode!=null){ if(i==index){ preNode.next=curNode.next; return true; } preNode=curNode; curNode=curNode.next; i++; } return true; } // Method 2, copy overwrite public int length(ListNode head){ int length=0; ListNode temp=head; while(temp!=null){ length++; temp=temp.next; } return length; } public void delete(ListNode head,ListNode deleteNode){ if(head==null || deleteNode==null){ return ; } if(deleteNode.next!=null){//The node to be deleted is not the tail node ListNode temp=deleteNode.next; deleteNode.val=temp.val; deleteNode.next=temp.next; temp=null; } else if(head==deleteNode){//The linked list has only one node deleteNode=null; head=null; } else{//The node to be deleted is the end node, traversal ListNode curNode=head; while(curNode.next!=deleteNode){ curNode=curNode.next; } curNode.next=null; deleteNode=null; } } }