19. Remove Nth Node From End of List 「删除链表的倒数第 N 个节点」

给定一个链表,删除链表的倒数第 N 个节点,并返回头节点。

举例:
给定的链表:1->2->3->4->5,n = 2。
在删除倒数第二个节点之后,链表变成了 1->2->3->5。

提示: 给定的 n 总是有效。你能只扫描一次链表来完成吗?

/*
 * 19. Remove Nth Node From End of List
 * https://leetcode.com/problems/remove-nth-node-from-end-of-list/
 * https://www.whosneo.com/19-remove-nth-node-from-end-of-list/
 */

public class RemoveNthFromEnd {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node = head;
        node.next = new ListNode(2);
        node = node.next;
        node.next = new ListNode(3);
        node = node.next;
        node.next = new ListNode(4);
        node = node.next;
        node.next = new ListNode(5);

        RemoveNthFromEnd solution = new RemoveNthFromEnd();
        node = solution.removeNthFromEnd(head, 2);
        solution.print(node);
    }

    private void print(ListNode node) {
        for (; node != null; node = node.next) {
            System.out.print(node.val);
            System.out.print("->");
        }
        System.out.println("null");
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummyHead = new ListNode(0), fast = dummyHead, slow = dummyHead;
        dummyHead.next = head;

        for (int i = 0; i < n; i++) {
            fast = fast.next;
        }

        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;

        return dummyHead.next;
    }
}

19. Remove Nth Node From End of List 「删除链表的倒数第 N 个节点」》有一个想法

  1. 席小欢

    看了你的文章,觉得非常不错…想与贵站互相友情链接

    建站知道网-http://wozhidaole.com.cn

    如果同意的话,回复一下后互相上链接!

    回复

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注