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 is defined as follows
#define ELEMTYPE INT
typedef struct lnode{
Elemtype data;
Lnode *next;
}lnode,*linklist;
Algorithm implementation:
lnode* Reciprocalknode (linklist &l,int k) {if (k<0) {printf ("K cannot be negative"); return NULL;} if (l==null) {printf ("single-linked list is empty"); return NULL;} lnode* p=l; lnode* Q=l;while (k>0) {p=p->next;if (p==null) {printf ("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;}
PS: This problem is identical to the solution of single-linked list without the lead node, but the single-linked list we usually use is the leading node.
Output single-linked list of the penultimate K-nodes