數(shù)據(jù)結(jié)構(gòu)與算法 | Leetcode 19. Remove Nth Node From

puppy-dog-cute-love-cat-mammal

原文鏈接:https://wangwei.one/posts/java-algoDS-Remove-Nth-Node-From-End-of-List.html

前面,我們實現(xiàn)了 兩個有序鏈表的合并 操作,本篇來聊聊,如何刪除一個鏈表的倒數(shù)第N個節(jié)點。

刪除單鏈表倒數(shù)第N個節(jié)點

Leetcode 19. Remove Nth Node From End of List

給定一個單鏈表,如: 1->2->3->4->5,要求刪除倒數(shù)第N個節(jié)點,假設(shè) N = 2,并返回頭節(jié)點。

則返回結(jié)果:1->2->3->5 .

解法一

這一題的難度標記為 medium,解法一比較容易想出來,我個人覺得難度不大。

思路

循環(huán)兩遍:

  1. 先遍歷一遍,求得整個鏈表的長度。
  2. 再遍歷一遍,當總長度len減去 n ,恰好等于循環(huán)的下標i時,就找到對應(yīng)要刪除的目標元素,將prev節(jié)點與next節(jié)點連接起來即可。

代碼

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null){
            return null;
        }
        int len = 0;
        for(ListNode curr = head ; curr != null;){
            len++;
            curr = curr.next;
        }
        
        if(len == 0){
            return null;
        }
        
        // remove head
        if(len == n){
            return head.next;
        }
        
        ListNode prev = null;
        int i = 0;
        for(ListNode curr = head; curr != null;){
            i++;
            prev = curr;
            curr = curr.next;
         
            if(i == (len - n)){
                prev.next = curr.next;
            }
        }
        return head;
    }
}

Leetcode測試的運行時間為6ms,超過了98.75%的java代碼。

解法二

這種解法,比較巧妙,沒有想出來,查了網(wǎng)上的解法,思路如下:

思路

只需要循環(huán)一遍,定義兩個指針,一個快指針,一個慢指針,讓快指針的巧好領(lǐng)先于慢指針n步。當快指針到達tail節(jié)點時,滿指針巧好就是我們需要刪除的目標元素。

代碼

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null){
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;
        for(int i = 0; i < n; i++){
            fast = fast.next;
        }
        
        if(fast == null){
            return slow.next;
        }
        
        ListNode prev = null;
        for(ListNode curr = slow; curr != null; ){
            // when fast arrived at tail, remove slow.
            if(fast == null){
                prev.next =  curr.next;
                break;
            }
            prev = curr;
            curr = curr.next;
            // move fast forward
            fast = fast.next;
        }
        return head;
    }
}

這段代碼在LeetCode上的測試結(jié)果與解法一的一樣。

這種解法與之前的 鏈表環(huán)檢測 題目中都使用到了快慢指針,用來定位特定的元素。

相關(guān)練習(xí)

參考資料

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

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

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