Delete a node in a single-chain table (Java version ).
Question: Delete the node p in the single-chain table L of the lead node. p is not the last node and requires the time complexity to be O (1 ).
Solution:
If the time complexity is not required to be O (1), we can find the precursor node of p and then delete p easily.
The time complexity is O (1). Because p is not the last node, we can delete the successor node of p when we know node p, then, we can assign the value of the successor node element of p to the value of the element of the p node.
ADT definition:
// The Node class LNode of the single-chain table {// to simplify the access to the single-chain table, the access permission for data items 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 null or the last node in the single-link table does not match the meaning of the question, LNode q = p is returned directly. next; // q is the successor node p. data = q. data; p. next = q. next; // delete node q from the single-chain table }}
Extended: If the deleted node p may be the last node, what should I do.
Solution: At this time, we can only ensure that the average time complexity of deleting nodes is O (1). When p is not the last node, the time complexity is O (1 ), when p is the last knot point, the time complexity is O (n ).
Algorithm Implementation:
Public class LinkListUtli {public static void deleteNode (LNode L, LNode p) {if (p = null | L = null) return; // if p is null or the single-chain table L is empty, if (p. next! = Null) // If p is not the last node {LNode q = p. next; // q is the successor node p. data = q. data; p. next = q. next; // delete node q} else from the single-chain table // If p is the last node {LNode pre = L; // use pre to represent the p's precursor node while (pre. next! = Null) // keep the pre with a successor node {if (pre. next = p) // If pre is the precursor node of p {pre. next = p. next; // delete node p from the single-chain table }}}}}