输出链表第k个节点

2018-10-31  本文已影响0人  怎样会更好

题目:

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

public ListNode FindKthToTail(ListNode head,int k) {
    if(head == null){
        return null;
    }
     if(k == 0){
        return null;
    }
    List<ListNode> list = new ArrayList<>();
    list.add(head);
    ListNode cur = head;
    while(cur.next != null){
        list.add(cur.next);
        cur = cur.next;
    }
    if(k > list.size()){
        return null;
    }
    return list.get(list.size()-k);
}

上一篇 下一篇

猜你喜欢

热点阅读