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;
    
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容