zoukankan      html  css  js  c++  java
  • 删除链表的倒数第 n 个节点

    难度: 中等

    leetcode地址:

    https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

    分析:

    1. 这题解题思路也不难,两个指针fast, slow,fast先走n步,然后两个一起走,fast走到最后为null的时候,slow正好走到倒数第n个节点,

    但是在单向链表中删除一个节点其实需要知道它的前直接点,所以我们需要少走一步,即走到fast为最后一个节点的时候就要停止,这个判断条件就是fast.next==null

    2. 另外我们需要分析一下特殊情况,当n正好等于链表长度时,这时实际上要删除的是头结点,这个判断条件是当fast 指针第一轮走n步之后,fast==null,这种情况直接返回head.next

    代码:

    public class RemoveNthFromEnd {
    public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode fast=head,slow=head;
    for(int i=0;i<n;i++){
    fast=fast.next;
    }
    if(fast==null){
    return head.next;
    }
    while(fast.next!=null){
    fast=fast.next;
    slow=slow.next;
    }
    slow.next=slow.next.next;
    return head;
    }
    }
  • 相关阅读:
    Mac安装zookeeper
    征途
    vue-配置文件
    数组去重
    判断身份证
    判断邮箱
    判断手机号是否正确
    JS 时间格式转换
    打印 print-js
    自"愚"自乐的云服务器
  • 原文地址:https://www.cnblogs.com/zhuge134/p/10926517.html
Copyright © 2011-2022 走看看