Sword se refiere a la oferta 22, el k-ésimo nodo de la parte inferior de la lista vinculada

  • análisis

      Puntero doble, deje que un puntero avance n pasos primero, luego el puntero rápido y el puntero lento se mueven hacia atrás al mismo tiempo, hasta que el puntero rápido se mueva al final de la lista vinculada.

  • Código
/**
 * 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* fast = head;
        while(k > 0 && fast != nullptr){
            fast = fast -> next;
            k--;
        }

        ListNode* slow = head;

        while(fast != nullptr){
            fast = fast -> next;
            slow = slow -> next;
        }

        return slow;
    }
};

 

Supongo que te gusta

Origin blog.csdn.net/xiaoan08133192/article/details/109004493
Recomendado
Clasificación