[剑指 offer] JT14---the kth node from the bottom in the linked list (shock!!! The relative movement of the two pointers makes it easy to solve the problem)

Sword Finger Offer Question 14

The topic is as follows

Insert picture description here

Idea and code

The first way of thinking is to take out the linked list and access it backwards. At first, I used vector to store the value, and then accessed it backwards. I found that what I need to access is a linked list, so I can’t use this method directly.

This place must be introducedDouble pointerUp!

Everyone should know the relative motion, that is, when the speed of two objects is the same, then the two of them areRelatively staticof. Then the problem-solving idea of ​​the ontology is like this. First let a pointer take k steps. If it is empty after k steps, it means that the pointer is not so long and returns to empty. After that, the two pointers are different by k steps, and they can go hand in hand. They justIt's always k steps away! When the fast pointer reaches the end, the slow pointer must be the kth node from the bottom of the linked list.

The farthest distance is not the world, but the distance between the two pointers, because there is no room for improvement!

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
    
    
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pHead ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* FindKthToTail(ListNode* pHead, int k) {
    
    
        // write code here
        if(!pHead||k<1) return nullptr;
        ListNode* fast=pHead;ListNode* slow=pHead;
        while(k>0){
    
    
            if(!fast) return nullptr;
            fast=fast->next;
            k--;
        }
        while(fast){
    
    
            fast=fast->next;
            slow=slow->next;
        }
        return slow;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42136832/article/details/114384521