第19题:Remove Nth Node From End of List

来源:互联网 发布:通过网络走群众路线 编辑:程序博客网 时间:2024/06/06 20:32

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.


题目要求:删除单链表的倒数第n个节点。


编程语言:javascript

解法:算法复杂度为O(n)  思路:建立一快一慢两个指针,其next指向单链表头结点。快指针先前进n步,然后两个指针同时前进,当快指针移动到底端时两个指针同时停止,此时慢指针指向倒数第n+1个节点。


/** * 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 startNode = new ListNode(0);    var slowNode = startNode;    var fastNode = startNode;    slowNode.next = head;        for(var i=1; i<=n+1; ++i)    {        fastNode = fastNode.next;    }        while(fastNode !== null)    {        fastNode = fastNode.next;        slowNode = slowNode.next;    }        slowNode.next = slowNode.next.next;        return startNode.next;        };


0 0