美文网首页
链表中倒数第k个结点

链表中倒数第k个结点

作者: 上杉丶零 | 来源:发表于2019-12-14 04:26 被阅读0次

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

package 剑指Offer.链表中倒数第k个结点;

public class Solution {
    public ListNode FindKthToTail(ListNode head, int k) {
        if (head == null || k <= 0) {
            return null;
        }

        ListNode aListNode = head;

        for (int i = 0; i < k - 1; i++) {
            aListNode = aListNode.next;
        }

        if (aListNode == null) {
            return null;
        }

        ListNode bListNode = head;

        while (aListNode.next != null) {
            aListNode = aListNode.next;
            bListNode = bListNode.next;
        }

        return bListNode;
    }
}

class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

相关文章

网友评论

      本文标题:链表中倒数第k个结点

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