LeetCode:19. 刪除鏈表的倒數(shù)第 N 個結(jié)點(中等)

問題鏈接

19. 刪除鏈表的倒數(shù)第 N 個結(jié)點

問題描述

給你一個鏈表,刪除鏈表的倒數(shù)第 n 個結(jié)點,并且返回鏈表的頭結(jié)點。

示例

解題思路

0.理解

在不考慮釋放被刪除節(jié)點對應的空間的情況下,我們只需要將倒數(shù)第n個節(jié)點的前節(jié)點指向倒數(shù)第n個節(jié)點的后節(jié)點即可。

1.借助數(shù)組

這可能算取巧,遍歷一遍鏈表,將鏈表中的每一個節(jié)點存入list,這時候你想怎么操作就怎么操作了......

2.雙指針

新建一個表頭,將兩個指針放在表頭往后遍歷:
一個指針先跑,使得兩個指針之間隔著n-1個節(jié)點;
當跑得快的指針跑到了最后一個節(jié)點時,另外一個指針跑到了倒數(shù)n+1個節(jié)點;
此時,讓倒數(shù)n+1個節(jié)點next指向next.next即可。

代碼示例(JAVA)

1.借助數(shù)組

/**
 * 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) {
        List<ListNode> nodeList = new ArrayList<>();
        ListNode node = head;
        while (node != null) {
            nodeList.add(node);
            node = node.next;
        }

        if (nodeList.size() == n) {
            return head.next;
        }
        nodeList.get(nodeList.size() - n - 1).next = n != 1 ? nodeList.get(nodeList.size() - n + 1) : null;
        return head;
    }
}

執(zhí)行結(jié)果

2.雙指針

/**
 * 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 newHead = new ListNode(0, head);
        ListNode first = head;
        ListNode second = newHead;

        for (int i = 0; i < n - 1; i++) {
            first = first.next;
        }
        while (first.next != null) {
            first = first.next;
            second = second.next;
        }

        second.next = second.next.next;
        return newHead.next;
    }
}

執(zhí)行結(jié)果

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容