zoukankan      html  css  js  c++  java
  • Remove Nth Node From End of List LeetCode Java

    描述
    Given a linked list, remove the n
    th 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.
    分析
    代码

     1 public static ListNode removeNthNodeFromEnd(ListNode head, int n) {
     2         if (head == null || n == 0)
     3             return head;
     4         ListNode fast = head, slow = head, p = head;
     5         int len = 1;
     6         while (p.next != null) {
     7             p = p.next;
     8             len++;
     9         }
    10         if (n == len) {
    11             return head.next;
    12         }
    13         n = n % len;
    14         for (int i = 0; i < len - n - 1; i++) {
    15             fast = fast.next; // fast会比i多进1
    16         }
    17         slow = fast.next;
    18         fast.next = slow.next;
    19         return head;
    20     }
  • 相关阅读:
    sqlldr、sqluldr2_w64案例
    查看oracle的sid和sevice_name
    杂记
    GAN学习
    Leetcode 第 217 场周赛
    牛客编程巅峰赛S2第4场
    SAR图像变化检测的一点想法
    Fire! UVA
    HDU
    HDU
  • 原文地址:https://www.cnblogs.com/ncznx/p/9160875.html
Copyright © 2011-2022 走看看