Leetcode: The sword refers to Offer 22. The kth node from the bottom in the linked list

The idea of ​​​​code implementation:
set two pointers (node1, node2) to point to the head node
. The first pointer takes k-1 steps (because the distance between the last k-th and the last node is k-1),
and then let node1 and node2 move forward at the same time Go until node1 goes to the last node
. At this point, node2 is exactly on the kth node from the bottom

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
    
    
        ListNode * node1 = head;
        ListNode * node2 = head;
        int flag = k;
        for(;flag>1 ; flag-- ){
    
    
            node1 = node1->next;
        }
        for(;node1->next!=nullptr; node1=node1->next){
    
    
            node2 = node2->next;
        }
        
        return node2;

    }
};

Guess you like

Origin blog.csdn.net/weixin_43579015/article/details/123271504