zoukankan      html  css  js  c++  java
  • Algorithm——Remove Nth Node From End of List

    Remove Nth Node From End of List

    Given a linked list, remove the n-th node from the end of list and return its head.

    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.

    Ans:

    /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
    /**
     * @param {ListNode} head
     * @param {number} n
     * @return {ListNode}
     */
    var removeNthFromEnd = function(head, n) {
        var temp = head;
        for (let i = 0; i < n; i++) {
            temp = temp.next;
        }
        
        if(!temp) return head.next; // n equals list.length
        
        var cur = head;
        while(temp.next) {
            temp = temp.next;
            cur = cur.next;
        }
        
        cur.next = cur.next.next;
        
        return head;
    };

    又是令人头秃的一天~

  • 相关阅读:
    数组操作
    HTML CSS 笔记
    jacascript 滚动scroll
    SEO优化技巧
    STP选举规则和例题
    3.1GSM-R的网络组成
    光缆的型号
    光缆的种类
    fdisk命令分区过程
    文件系统管理--挂载光盘与U盘
  • 原文地址:https://www.cnblogs.com/bbcfive/p/11409485.html
Copyright © 2011-2022 走看看