Output the k-th node and the reciprocal node of a single-chain table.
Question: Enter the single-chain table L of the leading node, and output the k-last node of the single-chain table. The last 0th nodes of a Single-linked table are the tail pointers of the single-linked table. Only one single-chain table can be traversed.
Solution:
If you do not need to traverse only one single-chain table at a time, we can traverse one single-chain table first and find the total number of its nodes n (including the first node ), therefore, the node of a single-chain table ranges from n-1 to 0th, and then traverses the single-chain table, the n-k-1 node that is accessed over time is the k node that is down in the single-linked list. Now we only need to traverse a single-chain table at a time. We can set two pointers, p and q. At the beginning, they all point to the header node, and p moves k bits backward. Finally, p, q moves backward at the same time until p is the last node, so q is what you want.
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 ("empty single-chain table"); return NULL;} LNode * p = L; LNode * q = L; while (k> 0) {p = p-> next; if (p = NULL) {printf ("the single-chain table is too short and there is no last k node"); return NULL ;}} while (p-> next! = NULL) {p = p-> next; q = q-> next;} return p ;}
PS: the solution to a single-chain table with no leading nodes is exactly the same, but the single-chain table we usually use is the leading node.