[leetcode-JavaScript]---19.删除链表的倒数第N个节点

栏目: JavaScript · 发布时间: 6年前

内容简介:给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。说明:给定的 n 保证是有效的。

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

示例:
    给定一个链表: 1->2->3->4->5, 和 n = 2.
    当删除了倒数第二个节点后,链表变为 1->2->3->5.
复制代码

说明:

给定的 n 保证是有效的。

思考

这道题要用双指针来实现。先用fast指针前进n,然后让slow从head开始和fast一起前进,直到fast到了末尾,此时slow的下一个节点就是要删除的节点。(另外,若fast一开始前进n就已经不在链表中了,说明要删除的节点正是head节点,那么直接返回head的下一个节点接口。)

解决方法

  • 双指针
/*
 * @lc app=leetcode.cn id=19 lang=javascript
 *
 * [19] 删除链表的倒数第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(n===0){
        return head;
    }
    let fast=head;
    let slow=head;
    while(n>0){
        fast=fast.next;
        n--;
    }
    if(fast===null){
        return head.next;
    }
    while(fast.next!=null){
        fast=fast.next;
        slow=slow.next;
    }
    slow.next=slow.next.next;
    return head;
};
复制代码

说明


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms for Image Processing and Computer Vision

Algorithms for Image Processing and Computer Vision

Parker, J. R. / 2010-12 / 687.00元

A cookbook of algorithms for common image processing applications Thanks to advances in computer hardware and software, algorithms have been developed that support sophisticated image processing with......一起来看看 《Algorithms for Image Processing and Computer Vision》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

html转js在线工具
html转js在线工具

html转js在线工具