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
  • 相关阅读:
    怎么为学生布置作业
    新学期的第一节Android课
    RUCSE小组博客列表
    test
    个人最终总结
    黄金点小游戏的设计与实现
    WordCount 程序的实现
    阅读下面程序,请回答如下问题:
    Visual Studio 2015的安装和简单的单元测试
    构建之法--软件工程学习随笔之二
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8128016.html
Copyright © 2011-2022 走看看