求解剑指Offer22 - 链表中倒数第K个节点


ListNode 的定义

package com.company;

public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }

    public ListNode setNext(ListNode next) {
        this.next = next;
        return next;
    }
    @Override
    public String toString() {
        return "ListNode{" +
                "val=" + val +
                '}';
    }
}

左右指针法

package com.company;

public class KthFromTail_Offer22 {
    public static  ListNode kthNodeFromEnd(ListNode head, int k){
        if( k <= 0 || head == null){
            return null;
        }
        ListNode pRight = head, pLeft = null;
        /* pRight moves k-1 steps from the start */
        for(int i=1; i