數據結構與算法 | Leetcode 19. Remove Nth Node From End of List

puppy-dog-cute-love-cat-mammal

原文連接:wangwei.one/posts/java-…html

前面,咱們實現了 兩個有序鏈表的合併 操做,本篇來聊聊,如何刪除一個鏈表的倒數第N個節點。java

刪除單鏈表倒數第N個節點

Leetcode 19. Remove Nth Node From End of Listnode

給定一個單鏈表,如: 1->2->3->4->5,要求刪除倒數第N個節點,假設 N = 2,並返回頭節點。算法

則返回結果:1->2->3->5 .數據結構

解法一

這一題的難度標記爲 medium,解法一比較容易想出來,我我的以爲難度不大。post

思路

循環兩遍:測試

  1. 先遍歷一遍,求得整個鏈表的長度。
  2. 再遍歷一遍,當總長度len減去 n ,剛好等於循環的下標i時,就找到對應要刪除的目標元素,將prev節點與next節點鏈接起來便可。

代碼

/** * 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代碼。spa

解法二

這種解法,比較巧妙,沒有想出來,查了網上的解法,思路以下:指針

思路

只須要循環一遍,定義兩個指針,一個快指針,一個慢指針,讓快指針的巧好領先於慢指針n步。當快指針到達tail節點時,滿指針巧好就是咱們須要刪除的目標元素。code

代碼

/** * 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上的測試結果與解法一的同樣。

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

相關練習

參考資料

相關文章
相關標籤/搜索