Output the k-th node and the reciprocal node of a single-chain table.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.