zoukankan      html  css  js  c++  java
  • LeetCode Valid Parentheses Remove Nth Node From End of List

        public ListNode removeNthFromEnd(ListNode head, int n) {
            if(head==null)
                return null;
            if(n==0)//如果n==0
                return head;
            Map<Integer,ListNode> map=new HashMap<Integer, ListNode>();
            int i=0;
            ListNode temp=head;
            do
            {
                map.put(++i, temp);
                temp=temp.next;
            }
            while(temp!=null);
            if(n>i)//if n > length
                return head;
            //now n>0 && n<=i
            map.remove(i+1-n);
            //if first
            if(n==1)
            {
                if(i==1)
                    return null;
                ListNode listNode=map.get(i-1);
                listNode.next=null;//假如只是将listNode置空,并没有什么卵用,结果会输出全部,因为前一个对象保存着该对象的引用
                return head;
            }
            //if end
            if(n==i)
                return map.get(2);
            //从n开始往后重新链接
            map.get(i-n).next=map.get(i+2-n);
            return head;
        }

    这里很需要注意的地方:

    1、map里面存放的是对象的引用,remove只是删除集合中对象的引用

    2、这道题中,假如只是将引用指向null,并不能将销毁对象本身,在链表中,还有其他地方引用了该对象。

    3、考虑问题要全面,以后每次做题要将所有情况都列出来!

  • 相关阅读:
    nuc970连接jlink进行单步调试的设置
    alsa utils工具使用
    用arm-linux-gcc v4.3.4交叉编译Qt4.8.3
    LNMP分离式部署
    MHA(下)
    MHA(上)
    PXE自动装机
    JumpServer
    FTP
    DNS
  • 原文地址:https://www.cnblogs.com/maydow/p/4628683.html
Copyright © 2011-2022 走看看