[Sword Finger 22] The Kth node from the bottom in the linked list

Method 1: Fast and slow pointers: time O(n), space O(1)

answer:

  1. Double pointer, one pointer moves k steps first, then the two pointers move backward at the same time, until the fast pointer is empty, return to the slow pointer
  2. k is greater than the summary points of the linked list: return to the head node, the fast pointer ran to empty
/**
 * 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) 
    {
    
    
        // 1.快慢指针:快指针先走k步,然后双指针同时向后走,直到快指针为空返回慢指针
        if (head == nullptr)
            return head;
        ListNode* fast = head;
        ListNode* slow = head;
        while (k-- && fast)
        {
    
    
            fast = fast->next;
        }
        while (fast)
        {
    
    
            slow = slow->next;
            fast = fast->next;
        }
        return slow;
    }
};

Guess you like

Origin blog.csdn.net/qq_45691748/article/details/113772139