LeetCode Remove Nth Node From End of List(019)解法總結

NewCoder1024發表於2020-03-29

描述

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.
複製程式碼

Note:

Given n will always be valid.

Follow up:

Could you do this in one pass?

思路

使用兩個指標避免回溯的情況,只需要讓兩個指標保持N的距離即可。

要注意連結串列長度為N時的特殊情況,即應當直接返回去除頭結點連結串列的情況。

/**
 * 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) {
        //定義兩個節點
        ListNode fir = head, sec = null;
        
        //將兩個節點距離拉開,其中if判斷N為連結串列長度的特殊情況
        for(int i = 0; i<n+1; i++){
            if(fir == null){
                return head.next;
            }
            fir = fir.next;
        }
        //非特殊情況下第二個指標的初始化
        sec = head;
        //兩個指標保持距離移動
        while(fir != null){
            fir = fir.next;
            sec = sec.next;
        }
        //進行刪除節點操作
        sec.next = sec.next.next;
        return head;
    }
}複製程式碼
Runtime: 0 ms, faster than 100.00% of Java online submissions for Remove Nth Node From End of List.
Memory Usage: 38.1 MB, less than 6.37% of Java online submissions for Remove Nth Node From End of List.

只進行一次遍歷可以減小很多時間消耗,而代價只是一個O(1)的空間消耗。


相關文章