代码改变世界

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

2022-05-18 21:01  jetwill  阅读(9)  评论(0编辑  收藏  举报

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<k; i++){
            if(pRight != null){
                pRight = pRight.next;
            }

        }
        while(pRight != null){
            if(pLeft == null){
                pLeft = head;
            }else{
                pLeft = pLeft.next;
            }
            pRight = pRight.next;
        }
        if(pLeft != null){
           return pLeft;
        }
        return null;
    }

    public static void main(String[] args){
        ListNode head = new ListNode(1);
        head.setNext(new ListNode(2))
                .setNext(new ListNode(3))
                .setNext(new ListNode(4))
                .setNext(new ListNode(5))
                .setNext(new ListNode(6));
        System.out.println(kthNodeFromEnd(head, 3));
        System.out.println(kthNodeFromEnd(head, 0));
        System.out.println(kthNodeFromEnd(head, 8));
    }
}