Title: Enter the single-linked table L of the lead node and output the reciprocal K-node in the single-linked list. The last No. 0 node of a single linked list is the tail pointer of the single linked list. Requires only one single linked list to traverse once.
Problem Solving Ideas:
If it is not required to traverse only one single linked list, we can first go through a single linked list, to find its total number of nodes N (including the head node), so the node of the single-linked list is from the penultimate n-1 to the No. 0, and then traverse the single-linked list, The n-k-1 node accessed during traversal is the reciprocal K-node in the single-linked list. Now it is required to traverse only one single-linked list, you can set two pointers p and Q, at the very beginning they all point to the Head node, then p moves the K-bit backwards, and finally the p,q moves backwards until p is the last node, then Q is the request.
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 {//For single-linked list of the last K nodes, the tail pointer is the bottom NO. 0 node public lnode reciprocalknode (Lnode L, int k) {if (K < 0) {System.ou T.println ("K cannot be negative"); return null;} if (L = = null) {SYSTEM.OUT.PRINTLN ("single-linked list is empty"); return null;} Lnode p = L; Lnode q = l;while (k > 0) {p = p.next;if (p = = null) {SYSTEM.OUT.PRINTLN ("single-linked list is too short, there is no reciprocal K-node"); return null;} while (p.next! = null) {p = P.next;q = Q.next;} return p;}
Output single-linked list of the last K nodes (Java version)