LeetCode-19~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
給定一個鏈表,移除從鏈表末尾起的第n個節(jié)點,并返回鏈表head

方法一

算法分析
  • 首先需要一個dummy節(jié)點,指向鏈表head位置,主要是為了在鏈表長度為1時簡化代碼。
  • 要刪除的節(jié)點在L-n+1位置(L為鏈表長度)。
  • 找到第L-n個節(jié)點,指向L-n+2個節(jié)點。
答案
/**
 * 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) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode current = head;
        int length = 0;//鏈表長度
        while (current != null) {
            length ++;//尋找鏈表長度
            current = current.next;
        }
        length = length - n;//到要被刪除位置的鏈表節(jié)點的前一個
        current = dummy;
        while (length > 0) {
            length --;
            current = current.next;
        }
        current.next = current.next.next;//將被刪除的節(jié)點前一個節(jié)點指向被刪除節(jié)點的下一個節(jié)點
        return dummy.next;
    }
}

方法二

算法分析
  • first、second兩個節(jié)點指向head
  • 移動first節(jié)點到與second相差n個節(jié)點的位置
  • 同時移動first、second直到first為null
  • 此時second的下一個節(jié)點是為要刪除的節(jié)點
答案
/**
 * 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) {
        ListNode dummy = new ListNode(0);
        ListNode first = dummy;
        ListNode second = dummy;
        dummy.next = head;
        
        for (int i = 1; i <= n + 1; i++) {
            first = first.next;//將first移到與second相差n個節(jié)點
        }
        while (first != null) {//first和second同時移動,直到first到最后一個節(jié)點的下一個節(jié)點
            first = first.next;
            second = second.next;
        }
        
        second.next = second.next.next;
        return dummy.next;
    }
}

參考

LeetCode

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容