博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
链表五:复杂链表的复制
阅读量:7190 次
发布时间:2019-06-29

本文共 2056 字,大约阅读时间需要 6 分钟。

/**

 * 题目:复杂链表的复制
 * 描述:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。
 *   (注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
 * 方案:方法一:  ① 遍历原链表,每次创建新节点,放入到HashMap里面;
 *     ② 遍历,进行节点连接; 
 *     ③ HashMap中,Value对应的值就是复制的链表
 *           方法二:  将原链表和复制的链表先放到一起,然后在进行拆分
 * */

public class Five {        public static RandomListNode one(RandomListNode phead) {        HashMap
hashMap = new HashMap<>(); RandomListNode cur; cur = phead; while(cur != null) { hashMap.put(cur, new RandomListNode(cur.label)); cur = cur.next; } cur = phead; while(cur != null) { hashMap.get(cur).next = hashMap.get(cur.next); hashMap.get(cur).random = hashMap.get(cur.random); cur = cur.next; } return hashMap.get(phead); } public static RandomListNode two(RandomListNode phead) { if(phead == null) { return null; } RandomListNode current = phead; //1.复制节点到A与B之间 A A* B , 连接任意节点和next节点 while(current !=null) { RandomListNode cloneNode = new RandomListNode(current.label); RandomListNode nextNode = current.next; RandomListNode randomNode = current.random == null? null:current.random ; cloneNode.next = nextNode; current.next = cloneNode; cloneNode.random = randomNode; current = nextNode; } //拆分 current = phead; RandomListNode pCloneHead = phead.next; while(current !=null ) { RandomListNode cloneNode = current.next; current.next = cloneNode.next; cloneNode.next = phead.next.next == null?null:phead.next.next; current = current.next; } return null; } static class RandomListNode{ int label; RandomListNode next; RandomListNode random; public RandomListNode(int label) { super(); this.label = label; } }}

 

转载于:https://www.cnblogs.com/ZeGod/p/9969342.html

你可能感兴趣的文章
Siege 3.0 正式版发布,压力测试工具
查看>>
cv:Mat MFC上显示 BitMatToWnd
查看>>
Excel 相关实用计算公式
查看>>
SQL*PLUS命令的使用大全
查看>>
hdu 2897(巴什博弈变形)
查看>>
hdu 1885(状态压缩+bfs)
查看>>
编程艺术第十六~第二十章:全排列/跳台阶/奇偶调序,及一致性Hash算法
查看>>
Hadoop1.2.0开发笔记(五)
查看>>
将SVN Server 创建成后台服务
查看>>
The type or namespace name 'Windows' does not exist in the namespace 'System'
查看>>
mysql索引无效且sending data耗时巨大原因分析
查看>>
ant打包成war包,通过jenkins自动ant构建到tomcat
查看>>
Questions about the AQS - Stack Overflow
查看>>
JSON和JSONP (含jQuery实例)(share)
查看>>
Cracking the coding interview--Q1.7
查看>>
MS SQL 中判断 数据库, 存储过程,表,临时表,视图,函数,用户,用户创建对象 等是否存在 SQL脚本...
查看>>
.Net中的加密解密
查看>>
sencha touch list(列表) item(单行)单击事件触发顺序
查看>>
网友对twisted deferr的理解
查看>>
Android + eclipse +ADT安装完全教程
查看>>