剑指offer 22 链表中倒数第K个节点.

简介

链表中倒数第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;
    }
}
Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/14830646.html