美文网首页
输出链表第k个节点

输出链表第k个节点

作者: 怎样会更好 | 来源:发表于2018-10-31 15:05 被阅读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);
}

相关文章

网友评论

      本文标题:输出链表第k个节点

      本文链接:https://www.haomeiwen.com/subject/cheatqtx.html