剑指Offer(书):链表的倒数第K个节点

题目:输入一个链表,输出该链表中倒数第k个结点。

分析:要注意三点:链表为空;链表个数小于k;k的值<=0;

public ListNode FindKthToTail(ListNode head,int k) {
    if(head==null || k<=0){
        return null;
    }
    ListNode pAhead = head;
    for( int i=0;i<k-1;i++){
        if(pAhead.next!=null){
            pAhead = pAhead.next;
        }else{
            return null;
        }
    }
    ListNode pBhead = head;
    while (pAhead.next!=null){
        pAhead=pAhead.next;
        pBhead=pBhead.next;
    }
    return pBhead;

}

 

posted @ 2018-08-08 15:36  liter7  阅读(83)  评论(0编辑  收藏  举报