[LeetCode] 19. 删除链表的倒数第N个节点 ☆☆☆

描述

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

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:

给定的 n 保证是有效的。

进阶:

你能尝试使用一趟扫描实现吗?

解析

用三指针,fast比slow快n个位置,slowPre是slow的pre节点。

代码

public static ListNode removeNthFromEnd(ListNode head, int n) {
        if (null == head || n <= 0) {
            return head;
        }
        ListNode slowPre = head;//比slow节点慢1个位置
        ListNode slow = head;//比fast节点慢n个位置
        ListNode fast = head;
        int slowCount = 0;
        while (null != fast) {
            if (n > 0) {
                fast = fast.next;
                n--;
                if (n == 0 && null == fast) {//当倒数第n个节点,刚好是首节点,直接返回head.next
                    return head.next;
                }
            } else {
                fast = fast.next;
                slow = slow.next;
                if (slowCount == 1) {
                    slowPre = slowPre.next;
                } else {
                    slowCount++;
                }
            }
        }
        slowPre.next = slow.next;
        return head;
    }

猜你喜欢

转载自www.cnblogs.com/fanguangdexiaoyuer/p/12069856.html