zoukankan      html  css  js  c++  java
  • Remove Nth Node From End Of List

     1 /**
     2  * Definition for singly-linked list.
     3  * function ListNode(val) {
     4  *     this.val = val;
     5  *     this.next = null;
     6  * }
     7  */
     8 /**
     9  * @param {ListNode} head
    10  * @param {number} n
    11  * @return {ListNode}
    12  */
    13 
    14 function ListNode(val) {
    15     this.val = val;
    16     this.next = null;
    17 }
    18 
    19 var removeNthFromEnd = function(head, n) {
    20     if (head === null) {
    21         return null;
    22     }
    23 
    24     var p1 = p2 = head;
    25 
    26     //p1先移动n次
    27     for (var i = 0; i < n; i++) {
    28         p1 = p1.next;
    29     }
    30 
    31     //要移除的是第一个元素
    32     if (p1 === null) {
    33         return head.next;
    34     }
    35 
    36     //当p1指向最后一个结点,则p2.next即为要删除的结点
    37     while (p1.next !== null) {
    38         p1 = p1.next;
    39         p2 = p2.next;
    40     }
    41 
    42     //删除倒数第n个结点
    43     p2.next = p2.next.next;
    44 
    45     return head;
    46 };
  • 相关阅读:
    Pick-up sticks
    The Doors
    Intersecting Lines
    Segments
    TOYS
    Palindrome
    Distinct Substrings
    Milk Patterns
    Musical Theme
    JavaScript基于时间的动画算法
  • 原文地址:https://www.cnblogs.com/huoteng/p/5029201.html
Copyright © 2011-2022 走看看