1. 程式人生 > >19. 刪除鏈表的倒數第N個節點

19. 刪除鏈表的倒數第N個節點

href 一個 標記 需要 沒有 lse problems 刪除 pro

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;
    }
}

19. 刪除鏈表的倒數第N個節點