[JOBDU] Topic 1517: List of the last K nodes in a list

Source: Internet
Author: User

Give a list of the head pointers, ask to find the bottom k node, and output the value of this node

Example:

First look at an example, the list is: 1 2 3 4 5 6, the bottom 2nd node is 5, the penultimate node is 6, and so on. The list here has a head node, which means that head->next is pointing to the first node. The data structure of the linked list is as follows:

1 // ListNode 2 struct Lnode {3     int key; 4     struct Lnode *Next; 5 }

Analysis:

We now only know the list of the head pointer, and the length of the list is unknown, then what to do?

One way that might come out of our mind first is to traverse the list first, to determine the length of the linked list, and then the countdown k node, which is the (length-k + 1) node. Of course this method can solve the problem, but it takes two times to traverse the list, if you go to the interview, you answer the interviewer, then this is obviously not the algorithm that the interviewer wants. So is there a better way to traverse the problem at once?

The answer is yes.

1. First, you can point to the head node with P1,P2 two pointers:

2. Then let P2 move the K (k=2) nodes forward first:

3. Then let P1,P2 move forward simultaneously, when P2 is empty, that is, P2 points to the next node (NULL) of the last node, the node that P1 points to is the penultimate K node:

Code:

1 //find the last k-th node of list2 intFindKey (Lnode *head,intk) {3Lnode *P1 =head;4Lnode *P2 =head;5     6     //p2 move on K nodes7      while(k-->0)8P2 = p2->Next;9 Ten     //Then P1 and P2 both move on until P2 = NULL One      while(p2) { AP1 = p1->Next; -P2 = p2->Next; -     } the      -     returnP1->key; -}

[JOBDU] Topic 1517: List of the last K nodes in a list

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.