Sword se refiere a la Oferta 22. El k-ésimo nodo desde la parte inferior en la lista vinculada: doble puntero / recursión

22. El k-ésimo nodo de la parte inferior de la lista vinculada

Puntero doble

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode i=head;
        ListNode j=head;
        int t=k-1;
        while(t>0){
            j=j.next;
            --t;
        }
        while(j.next!=null){
            j=j.next;
            i=i.next;
        }
        return i; 
    }
}

Recursividad

class Solution {
    int size;
    public ListNode getKthFromEnd(ListNode head, int k) {
        if(head==null) return head;
        ListNode node=getKthFromEnd(head.next,k);
        size++;
        if(size<k)
            return null;
        else if(size==k)
            return head;
        else
            return node;
    }
}

 

Supongo que te gusta

Origin blog.csdn.net/qq_41041762/article/details/108061319
Recomendado
Clasificación