Output single-linked list of the penultimate K-nodes

Source: Internet
Author: User

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

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.