1. 程式人生 > 實用技巧 >力扣每日一題:刪除連結串列的倒數第N個節點

力扣每日一題:刪除連結串列的倒數第N個節點

題目連結
思路有兩個:

  • 遍歷一遍連結串列得到整個連結串列長度L,再遍歷一次到L-n-1的地方進行刪除節點
  • 用快慢指標,相隔距離n
    實現過程:
  • 剛開始用的是在原連結串列內進行操作,加上一些特殊情況,例如只有一個節點和刪除的是第一個位置時。
 /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode tmp = head;
            ListNode mark = head;
            int cnt = 0;
            while (head != null) {
                if (cnt > n)
                    mark = mark.next;
                cnt++;
                head = head.next;
            }
            if (cnt <= 1)//只有一個元素或為空
                return null;
            if (cnt == n)
                return tmp.next;
            mark.next = mark.next.next;
            return tmp;
        }
    }
  • 通過檢視題解,回憶起一種經常在連結串列中使用的技巧——設定一個啞巴節點dummy,於是不用額外判斷邊界條件。
/**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode dummy = new ListNode(0, head);//啞巴節點
            ListNode begin = dummy, end = head;
            int cnt = 0;
            while (end != null) {
                cnt++;
                if (cnt > n)
                    begin = begin.next;
                end = end.next;
            }
            begin.next = begin.next.next;
            return dummy.next;
        }
    }