leetcode—Remove Nth Node From End of List

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

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode preHead = new ListNode(0);
        ListNode first = head;
        ListNode sec = head;
        int i=0;
        while(first!=null && i<n){
            first = first.next;
            i++;
        }
        if(i<n) return head;
        if(first==null) return head.next;
        while(first.next!=null){
            first = first.next;
            sec = sec.next;
        }
        sec.next = sec.next.next;
        return head;
    }
}

**這道題是鏈表基本操作,主要問題就是如何得到鏈表的倒數第n個結點,思路就是先用一個first指針走n步,然後再來一個sec從頭開始和first同時向後走,當first走到鏈表末尾的時候(注意這裏的末尾是鏈表的最後一個指針,不是空指針),sec指針即爲倒數第n個結點。算法的時間複雜度是O(鏈表的長度),空間複雜度是O(1)
注意的情況是:倒數第n個結點是頭節點
倒數第n個結點不是鏈表中**

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章