zoukankan      html  css  js  c++  java
  • 19. Remove Nth Node From End of List

    19. Remove Nth Node From End of List

    Given a linked list, remove the nth 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 /**
     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 var removeNthFromEnd = function(head, n) {
    14     
    15     //这种操作链表的,又不知道链表长度的问题,往往也是用双指针去做,比如还有快慢指针判断链表环
    16     
    17     
    18     //本题还要考虑几种特殊情况,比如说删除头节点 和 删除尾节点
    19     
    20     //我们会有3个指针,1个是head的头指针,1个是fir指针,它会先走n补,作为预处理,las指针比fir少走n步
    21     
    22     //首先考虑什么时候是删除尾节点的?  n==1 的时候是删除伪结点的。那直接移到最后,再将倒数第二个的next ==null 即可
    23     
    24     //那什么时候是删除头结点的? 很明显就是fir指针先走了n-1步之后,它的next直接是null了,这种情况就是删除头结点的。我们只需要返回head.next即可
    25     
    26     //还有一个问题。如果链表中只有1个节点,怎么办?此时n必然为1。预处理好像解决不了问题。
    27 
    28     var fir = head;  //先走n步
    29     var las = fir;   
    30     
    31     
    32     
    33     //这种是处理单节点的链表
    34     if(n == 1 && fir.next == null){
    35         return null;
    36     }
    37     
    38     //不然就是超过2个节点以上的
    39     
    40     for(var i = 0;i<n;i++){
    41         
    42         fir = fir.next;
    43         
    44     }
    45     
    46     //说明是删除头指针
    47     if(fir == null){
    48         return head.next;
    49     }
    50     
    51     
    52     
    53     
    54     //先走了n步的next为null时,就是las到达目标位置
    55     while(fir.next){
    56        las = las.next;
    57        fir = fir.next;
    58     }
    59     
    60     //删除las.next;
    61     las.next = las.next.next;
    62     
    63     return head;
    64 };
  • 相关阅读:
    acm入门 杭电1001题 有关溢出的考虑
    面向对象课后深入学习(C++ 类的静态成员详细讲解)
    Eclipse中导入项目后js报错解决方法
    mysql用户链接数
    配置服务器nginx 教程
    eclipse如何新建项目发布到git
    获取当天开始时间结束时间
    pdf在线加载·
    springmvc配置详解 教程
    hibulder中使用git教程
  • 原文地址:https://www.cnblogs.com/huenchao/p/7656097.html
Copyright © 2011-2022 走看看