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.node

For example,this

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.code

這題也是攜程18年暑假實習生的筆試題。rem

最開始想的解法就是,先循環求鏈表的長度,再用長度-n,再循環一次就能移除該結點。結果對的,可是超時了。代碼以下:it

/**
 * 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) {
    let start = new ListNode(null);
    start.next = head;
    let len = 0,
        current = null,
        del = null;
    if(head === null){
        len = 0;
    }else{
        current = head;
        len = 1;
        while(current.next){
            len++;
        }
    }
    let position = len - n;
    if(position > -1 && position < len){
        current = head;
        let previous,
            index = 0;
        // 移除第一項
        if(position === 0){
            head = current.next;
        }else{
            while(index < position){
                previous = current;
                current = current.next;
                index++;
            }
            del = current;
            previous.next = current.next;
        }
        len--;
        return start.next;
    }else{
        return null;
    }
};

後來看了別人的最佳解法,以爲本身太蠢了。
最佳解法:用兩個指針,第一個指針slow的next指向第一個節點,第二個指針fast指向第n+1個結點,而後兩個指針同時後移,直到fast指針指向null,這個時候slow指針指向要刪除結點的前一個節點,使用slow.next = slow.next.next刪除結點。再返回整個鏈表。代碼以下:io

/**
 * 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) {
    var start = new ListNode(null);
    start.next = head;
    let slow = start,
        fast = head;
    slow.next = head;
    
    if(head.next === null){
        return null
    }
    
    for(var i = 0; i < n; i++){
        fast = fast.next;
    }
    
    while(fast !== null){
        slow = slow.next;
        fast = fast.next;
    }
    
    slow.next = slow.next.next;
    return start.next;
};
相關文章
相關標籤/搜索