Title: The node in the single-linked list L that removes the lead node p,p is not the last node, requiring a time complexity of O (1).
Problem Solving Ideas:
If the time complexity is not required to be O (1), we can find the precursor node of P and then easily delete p.
Now the time complexity is called O (1), because P is not the last node, knowing the node p we can delete the successor node of P, then we can assign the value of the subsequent node element of P to the value of the P node element.
ADT Definition:
Single-linked list of node class lnode{//to simplify access to a single-linked list, the data entry in the node is set to Publicpublic int data;public lnode next;}
Algorithm implementation:
public class Linklistutli {public static void Deletenode (Lnode p) {if (p==null| | P.next==null) return;//if P is empty or the last node in the single-linked list does not conform to test instructions, the Lnode q=p.next;//q is returned directly to the successor node of P p.data=q.data;p.next=q.next;// Delete Node Q} from a single linked list
Expand: What to do if the deleted node p may be the last node.
Solution thinking: At this point can only ensure that the average time to delete the node complexity is O (1), when P is not the last node, the complexity is O (1), when P is the last node, the time complexity of O (n).
algorithm implementation:
public class Linklistutli {public static void Deletenode (Lnode l,lnode p) {if (p==null| | L==null) return;//if P is empty or the single-linked list L is empty does not conform to test instructions, return directly if (p.next! = null)//If p is not the last node {Lnode q=p.next;//q is the successor of P p.data= Q.data; p.next=q.next;//Delete a node from a single linked list Q}else//If p is the last node {Lnode pre=l;//uses the pre to represent the precursor node of P while (pre.next! = null)//Hold the pre has a successor node {if ( PRE.NEXT==P)//If the pre is the precursor node of p {pre.next=p.next;//Delete node p from the single-linked list}}}}
Delete a single-linked list node (Java edition)