找出单链表倒数第N个

思路

记录两个头结点A,B。
A先走N步,然后AB一起走,知道A走到末尾。去除B的next既是倒数第N个。

代码

public static Node searchLast(Node node, int lastNum) {
        Node headNode = node;
        for (int i = 0; i < lastNum; i++) {
            node = node.next;
        }
        while (node.next != null) {
            node = node.next;
            headNode = headNode.next;
        }
        return headNode.next;
}

其余代码

    /**
     * 初始化
     *
     * @return
     */
    public static LinkList init() {
        LinkList linkList = new LinkList();
        linkList.head = new Node();
        // 记住头结点
        Node h = linkList.head;
        for (int i = 0; i < 10; i++) {
            linkList.head.data = i;
            // 不初始化尾节点
            if (i < 9) {
                linkList.head.next = new Node();
                linkList.head = linkList.head.next;
            }
        }
        linkList.head = h;
        return linkList;
    }

    public static class Node {

        int data;

        Node next;

    }

    public static class LinkList {

        Node head;
    }

猜你喜欢

转载自blog.csdn.net/weixin_33691598/article/details/86844786
今日推荐