LeetCode- 19 刪除連結串列的倒數第N個節點

晓枫的春天發表於2024-04-17

題目地址

https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/

參考實現

 /**
     * 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; }
     * }
     */
    /**
     * 透過連結串列長度 進行處理
     *
     * @param head
     * @param n
     * @return
     */
    public static ListNode removeNthFromEnd1(ListNode head, int n) {
        ListNode dumny = new ListNode(0, head);
        ListNode current = dumny;
        for (int i = 1; i < getLenth1(head) - n + 1; i++) {
            current = current.next;
        }
        //執行刪除
        current.next = current.next.next;
        return dumny.next;

    }

    /**
     * 獲取連結串列大小
     *
     * @param head
     * @return
     */
    public static int getLenth1(ListNode head) {
        int length = 0;
        while (head != null) {
            head = head.next;
            length++;
        }

        return length;
    }

    /**
     * 利用棧特性處理
     *
     * @param head
     * @param n
     * @return
     */
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dumny = new ListNode(0, head);
        Deque<ListNode> stack = (Deque<ListNode>) new LinkedList<ListNode>();
        ListNode current = dumny;
        while (current != null) {
            stack.push(current);
            current = current.next;
        }

        for (int i = 0; i < n; i++) {
            stack.pop();
        }

        ListNode peek = stack.peek();
        peek.next = peek.next.next;
        return dumny.next;
    }

    /**
     * 雙指標處理
     *
     * @param head
     * @param n
     * @return
     */
    public static ListNode removeNthFromEnd3(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        ListNode first = head;
        ListNode second = dummy;
        for (int i = 0; i < n; i++) {
            first = first.next;
        }
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        second.next = second.next.next;
        return dummy.next;
    }

相關文章