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個位置,當第一個指針到頭時,第二個指針所指的下一個就是要刪的節點。有兩個特殊情況要注意,一個是要刪的是頭節點,一個是鏈表里就一個節點。

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function(head, n) {
    if (head === null)
        return head;
    if (head.next===null)
        return null;
    var pointer1 = head;
    var pointer2 = head;
    var num = 1;
    while (pointer1.next!==null) {
        if (num>n) 
            pointer2 = pointer2.next;
        else
            num++;
        pointer1 = pointer1.next;
    }
    if (n === num) 
        return pointer2.next;
    else
        pointer2.next = pointer2.next.next;
    return head;
    
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容