LeetCode Ex19 Remove Nth Node From End of List

Remove Nth Node From End of List

Given a linked list, remove the n-th node from the end of list and return its head.

Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.

题目

该题要求删除一个链表的第倒数第N个节点,也就是说删除正数第L-n+1个节点(L为链表的长度)

有两种方法,分别是遍历链表一次和两次

两次:第一次遍历先获取链表的总长度,第二次遍历当到第L-n+1个时,前一个节点的next指向这个节点.next.netx即可。

Two pass

    public ListNode removeNthFromEnd2(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        int length = 0;
        ListNode first = head;
        while (first != null) {
            length++;
            first = first.next;
        }
        length -= n;
        first = dummy;
        while (length > 0) {
            length--;
            first = first.next;
        }
        first.next = first.next.next;
        return dummy.next;
    }

一次:创建两个指针,先让指针1走n步,这时候两个指针相差n个节点,然后两个指针同时移动,当指针1走到链表结尾时,指针2正好在要删除的节点的前一个节点,这时候指向.next.next即可

One pass

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode first = dummy;
        ListNode second = dummy;
        for (int i = 1; i <= n + 1; i++) {
            first = first.next;
        }
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        second.next = second.next.next;
        return dummy.next;
    }

猜你喜欢

转载自blog.csdn.net/weixin_34129145/article/details/87156250