• 复杂链表的复制




    我的题解

    /*
    // Definition for a Node.
    class Node {
        int val;
        Node next;
        Node random;
    
        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }
    */
    class Solution {
        public Node copyRandomList(Node head) {
            if(head==null) return null;
            Node tmp = head,headA,headB;
            headA =new Node(head.val);
            headB=headA;
            while(tmp!=null){//安排好next指针(先让节点连起来)
               tmp=tmp.next;
               if(tmp==null) break; 
               Node cur =new Node(tmp.val);
               headA.next=cur;
               headA=cur;
            }
            tmp=head;
            Node cur=headB;
           
            while(tmp!=null){//安排random指针
                //初始化数据
                int i=0,j=0;
                headA=headB;
                Node tmp1=head;
                while(tmp1!=null){//双重循环确定每一个节点的random指向的位置(用计数器记录)
                    if(tmp.random==null){
                        i=-1;break;
                    } 
                    i++;
                    if(tmp.random==tmp1){
                        break;
                    }
                    tmp1=tmp1.next;
                }
                
                while(headA!=null){
                if(i==-1) break;
                 j++;
                 if(i==j){//移动到之前计数的相同位置直接进行指向
                     cur.random=headA;
                     break;
                 }
                 headA=headA.next;
                }
                tmp=tmp.next;
                cur=cur.next;
            }
            return headB;
        }
    }
    

    官方题解

    /*
    // Definition for a Node.
    class Node {
        int val;
        Node next;
        Node random;
    
        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }
    */
    class Solution {
        public Node copyRandomList(Node head) {
            if(head == null) return head;
            Map<Node,Node> m = new HashMap<>();
            Node cur = head;
            while(cur != null){
                m.put(cur,new Node(cur.val));
                cur = cur.next;
            }
            cur = head;
            while(cur != null){
                m.get(cur).next = m.get(cur.next);
                m.get(cur).random = m.get(cur.random);
                cur = cur.next;
            }
            return m.get(head);
    
        }
    }
    
    

    不一样的烟火
  • 相关阅读:
    WPF中更改键盘默认指令小结
    WPF自己喜欢用的数据验证方式
    重写Windows基类,自定义WPF窗口,实现改回车键为TAB
    用CSS控制表格的框格线
    获取当前鼠标的坐标
    SQL 中的转义字符
    資料站點
    jquery 弹出浮层(div) + 遮蔽层
    Jquery放大镜插件[JMagazine]使用参数简介
    邏輯題 交通事故篇
  • 原文地址:https://www.cnblogs.com/cstdio1/p/13301260.html
Copyright © 2020-2023  润新知