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

19. 删除链表的倒数第N个节点

1A,开心~

注意,题目有进阶要求,只允许扫链表1次,
很多链表题跟这个思路一样,在遍历链表的时候,维护一个距离与当前头指针为(n+1)的尾巴标记P即可,当扫到链表结尾的时候,此时P正好指向待删除节点的前一个节点

注意几个细节处理:
0:注意P的初始化
1:n>链表长度时,无需处理
2:n == 链表长度时,P此时仍没有指向任何一个节点,需要特判把头节点删除

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode org = head;
        ListNode ans = null;

        int cnt = 0;

        while (head != null) {
            head = head.next;
            cnt++;
            if (cnt > n) {
                if (ans == null) ans = org;
                else {
                    ans = ans.next;
                }
            }
        }

        if (ans != null && n > 0) {
            if (n == 1) {
                ans.next = null;
            } else {
                ans.next = ans.next.next;
            }
        }

        if (cnt == n) {
            org = org.next;
        }

        return org;
    }
}

猜你喜欢

转载自www.cnblogs.com/acbingo/p/9250754.html