剑指 Offer 22. 链表中倒数第k个节点

class Solution {
    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode p = head;
        int count = 0;
        while(p!=null){
            count++;
            p = p.next;
        }
        if(k>count) return null;
        int m = count - k ;
        while(m>0){
            head = head.next;
            m--;
        }
        return head;
    }
}

 

先确定结点总数,再遍历。


 

方法二:

一次遍历,两个指针

class Solution {
    public ListNode getKthFromEnd(ListNode head, int k) {
        if(head == null || k == 0) return null;
        ListNode p = head;
        ListNode q = head;
        while (p!=null){
            while(k>0){
                if(p == null) return null;
                p = p.next;
                k--;
            }
            if(p != null) {
                p = p.next;
                q = q.next;
            }
        }
        return q;
    }
}

 

posted @ 2020-08-10 16:28  欣姐姐  阅读(112)  评论(0编辑  收藏  举报