zoukankan      html  css  js  c++  java
  • 复杂链表的复制



    我的题解

    /*
    // 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);
    
        }
    }
    
    

    不一样的烟火
  • 相关阅读:
    BizTalk2010简介
    各大类库的类工厂
    全国城市三级级联菜单(java+Ajax+jQuery)
    gcc编译系统
    通用排行榜组件
    本地化中文示例代码需求调查
    PortalBasic Java Web 应用开发框架(源码、示例及文档)
    FFLIB 框架
    ORM/IOC框架设计感悟
    个人日记
  • 原文地址:https://www.cnblogs.com/cstdio1/p/13301260.html
Copyright © 2011-2022 走看看