zoukankan      html  css  js  c++  java
  • Remove Nth Node From End of List从尾部开始删除第N个节点

    [抄题]:

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

    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.

    [思维问题]:

    [一句话思路]:

    快指针走n步,慢指针再走,形成线段差

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    1. dummy,corner case已经成为标配了
    2. preDelete要从最前开始指,指向dummy
    3. 只需要写head.next != null,因为一次只走一步

    [总结]:

    1. 只需要写head.next != null,因为一次只走一步

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [英文数据结构,为什么不用别的数据结构]:

    [其他解法]:

    [Follow Up]:

    [题目变变变]:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            if (n <= 0) {
                return head;
            }
            for(int i = 0; i < n; i++) {
                head = head.next;
            }
            
            ListNode preDelete = dummy;
            while(head != null) {
                head = head.next;
                preDelete = preDelete.next;
            }
            preDelete.next = preDelete.next.next;
            
            return dummy.next;
        }
    }
    View Code
  • 相关阅读:
    cf1043C. Smallest Word(贪心)
    洛谷P1081 开车旅行(倍增)
    NOI.AC NOIP2018 全国热身赛 第四场
    cf444E. DZY Loves Planting(并查集)
    NOI.AC NOIP模拟赛R3解题报告
    中国第一计算机编程高手横瓜的天才求职之路异常艰辛,天妒奇才呀
    C语言全局未初始化数据段分析
    js问题总结
    ios7新增基础类库以及OC新特性
    jquery.post用法
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8128016.html
Copyright © 2011-2022 走看看