面试题21:链表中倒数第K个节点

2018-12-27  本文已影响0人  灰化肥发黑会挥发

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

  1. 输入链表为空。
  2. K的值大于链表长度。
  3. K的值不能为0。
public class FindKList {
    public int Find(ListNode head,int k){
        if(k==0||head==null)
            return -1;
        ListNode pAhead = head;
        ListNode pBehind = head;
        for(int i=0;i<K-1;i++){
            if(pAhead.next!=null)
                pAhead = pAhead.next;
            else
                return -1;
        }
        while(pAhead!=null){
            pAhead = pAhead.next;
            pBehind = pBehind.next;
        }
        return pBehind.val;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读