【Leetcode Algorithm】Remove Nth Node From End of List

題目:

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

For 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.
Try to do this in one pass.(意思是O(n)複雜度)


剛開始只想到用兩個指針,中間隔n-1步,當走在前面的指針到達尾部時,那麼後一個節點一定指向倒數第n個節點。這樣還得記錄倒數第n個節點的前驅節點,從而才能刪除倒數第n個節點。但是,這樣遇到的問題是,如果指向的該倒數第n個節點是head節點(沒有前驅節點了),那麼就沒法刪除了。改進的方法就是,從一開始就新建一個節點behindhead,使其指向頭結點。最後返回的時候返回behindhead.next就好了

代碼:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        //新建一個節點指向head
        ListNode behindhead = new ListNode(0);
        behindhead.next = head;
        //建兩個指針,指針ahead一個指向head節點
        ListNode ahead = head;
        //指針behind指向behindhead節點
        ListNode behind = behindhead;
        //指針ahead需要向前移動n-1步
        for(int i=0; i<n-1; i++){
            if(ahead.next!=null){
                ahead = ahead.next;
            }
        }
        //當指針ahead沒有到達尾部時,指針ahead和behind都往前移動
        while(ahead.next!=null){
            ahead = ahead.next;
            behind = behind.next;
        }
        //刪除behind後面的節點
        behind.next = behind.next.next;
        return behindhead.next;
    }
}


發佈了36 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章