链表中倒数第k个结点

2019-12-14  本文已影响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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读