zoukankan      html  css  js  c++  java
  • 分解让复杂问题简单化:复杂链表的复制

    输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

    思路:首先遍历一遍原链表,创建新链表(赋值label和next),用map关联对应结点;再遍历一遍,更新新链表的random指针。(注意map中应有NULL ----> NULL的映射)

    import java.util.HashMap;
    import java.util.Map;
    
    /*
    public class RandomListNode {
        int label;
        RandomListNode next = null;
        RandomListNode random = null;
    
        RandomListNode(int label) {
            this.label = label;
        }
    }
    */
    public class Solution {
        public RandomListNode Clone(RandomListNode pHead)
        {
            if (pHead == null) {
                return null;
            }
            RandomListNode pHead1 = pHead;
            RandomListNode pHead2 = new RandomListNode(pHead.label);
            RandomListNode newHead = pHead2;
            Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
            map.put(pHead1, pHead2);
            while (pHead1 != null) {
                if (pHead1.next != null) {
                    pHead2.next = new RandomListNode(pHead1.next.label);
                } else {
                    pHead2.next = null;
                }
                pHead1 = pHead1.next;
                pHead2 = pHead2.next;
                map.put(pHead1, pHead2);
            }
            pHead1 = pHead;
            pHead2 = newHead;
            while (pHead1 != null) {
                pHead2.random = map.get(pHead1.random);
                pHead1 = pHead1.next;
                pHead2 = pHead2.next;
            }
            return newHead;        
        }
    }
  • 相关阅读:
    冒泡排序算法分析和实现
    选择排序算法分析与实现
    nio和 bio
    TCP三次握手
    IE input X 去掉文本框的叉叉和密码输入框的眼睛图标
    <%#eval() %>和<%#bind() %> 的区别
    <%#Eval() %>的常用方法
    C#(ASP.net)从其他网站抓取内容并截取有用信息
    JQuery写的一个简单的分页插件-2
    简单实用的jQuery分页插件
  • 原文地址:https://www.cnblogs.com/SaraMoring/p/5820763.html
Copyright © 2011-2022 走看看