1. 程式人生 > >【數據結構】算法 LinkList (Remove Nth Node From End of List)

【數據結構】算法 LinkList (Remove Nth Node From End of List)

復雜 div 節點 ++ from while class 刪除鏈表 保持

刪除鏈表中倒數第n個節點

時間復雜度要控制在O(n)
Solution:
設置2個指針,一個用於確定刪除節點的位置,一個用於計算倒數間距n。移動時保持2個指針同時移動。

 public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head==null) return null;
        ListNode pre = head;
        ListNode cur = head; 
        for(int i=0;i<n;++i){
            cur = cur.next;
             
if(cur==null) { return head.next; } } while(cur.next!=null){ cur=cur.next; pre= pre.next; } pre.next = pre.next.next; return head; }

【數據結構】算法 LinkList (Remove Nth Node From End of List)