简介

链表中倒数第K个节点.

思路

双指针, 然后一个指针延迟运行.

code

class Solution {
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
        ListNode *p = head;
        ListNode *pk = head;
        int index = 0;
        bool check = false;
        while(p){
            p = p->next;
            index ++;
            if(index == k) check = true;
            if(index > k){
                
                pk=pk->next;
            }
        }
        if(check) return pk;
        return NULL;
    }
};

java

// 可以让一个指针先走, 真的方便.

class Solution {
    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode former = head, latter = head;
        for(itn i = 0; i<k; i++){
            former = former.next;
        }
        while(former != null) {
            former = former.next;
            latter = latter.next;
        }
        return latter;
    }
}
posted on 2021-05-31 11:29  HDU李少帅  阅读(26)  评论(0编辑  收藏  举报