zoukankan      html  css  js  c++  java
  • 领扣(LeetCode)删除链表的倒数第N个节点 个人题解

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

    示例:

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

    说明:

    给定的 n 保证是有效的。

    进阶:

    你能尝试使用一趟扫描实现吗?

    快慢针的思想。快针先移动N个步长,然后两个针一起移动,快针结束时,慢针指向倒数第N+1个节点。然后就是简单的删除节点操作了。这里需要注意删除的节点是第一个节点的特判。

    这里由于使用了JAVA,对返回head突然有了新的疑惑,为什么操作fast和slow会影响到head的内容。这里需要认真学习一下。

    代码如下:

     1 class Solution {
     2     public ListNode removeNthFromEnd(ListNode head, int n) {
     3         if (head == null)
     4             return null;
     5         ListNode slow = head;
     6         ListNode fast = head;
     7         while (n >= 1 && fast.next != null) {
     8             fast = fast.next;
     9             n--;
    10         }
    11         if (n > 1)
    12             return head;
    13         if (n == 1)
    14             return head.next;
    15         while (fast.next != null) {
    16             slow = slow.next;
    17             fast = fast.next;
    18         }
    19         slow.next = slow.next.next;
    20         return head;
    21     }
    22 }
  • 相关阅读:
    名字空间,L,E, G , B 作用域, 内置电池
    lambda表达式
    表达式与声明的区别。
    jupyter book的使用
    centos7一键安装cacti_1.2.16版本
    docker修改阿里云镜像加速器
    centos单网卡多ip,被动模式
    centos同步时间
    centos7.x制作bond
    centos 6.X制作bond
  • 原文地址:https://www.cnblogs.com/axiangcoding/p/10068323.html
Copyright © 2011-2022 走看看