如何找出单链表中的倒数第K个元素--Java版

如何找出单链表中的倒数第K个元素--Java版_第1张图片

public class Node {
    public int data;
    public Node next;

    public Node(int data) {
        this.data = data;
    }
}

    public Node removeLastKthNode(Node head, int lastKth) {
        //排除异常情况
        if (head == null || lastKth < 1) {
            return head;
        }
        //cur每走一步,lastKth-1,根据lastKth的值来确定是哪种情况
        Node cur = head;
        while (cur != null) {
            lastKth--;
            cur = cur.next;
        }
        //这时,cur已经走出链表
        if (lastKth == 0) {//情况②
            head = head.next;
        }
        if (lastKth < 0) {//情况③
            cur = head;
            while (++lastKth != 0) {
                cur = cur.next;
            }
            cur.next = cur.next.next;
        }
        return head;//情况①
    }

你可能感兴趣的:(数据结构与算法--Java版)