LinkedList:给定一个链表,从后删除第几个结点

public static ListNode removeNthFromEnd(ListNode head, int n) {
        int size = 0;
        ListNode newListNode = new ListNode(0);
        newListNode.next = head;
        ListNode node = head;
        ListNode cur = newListNode;
        while (node != null) {
            size++;
            node = node.next;
        }
        if (size == 1 && n == 1) {
            return null;
        }

        int count = size - n;
        for (int i = 0; i < count; i++) {
            cur = cur.next;
        }
        if (cur.next != null) {
            cur.next = cur.next.next;
        }

        return newListNode.next;

    }

你可能感兴趣的:(LinkedList:给定一个链表,从后删除第几个结点)