复杂链表的复制(复制含有随机指针节点的链表)
来源:互联网 发布:c语言指针和引用 编辑:程序博客网 时间:2024/05/20 23:38
复杂链表的复制(复制含有随机指针节点的链表)程序员代码面试指南(左程云)读书笔记
第三章
题目:
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
public class ListRandom {
class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
方法一: 用哈希表,将链表遍历一遍,key和value的值对应关系如下
然后再遍历一次链表,设置复制链表的next和random指针
public RandomListNode Clone2(RandomListNode pHead)
{
HashMap<RandomListNode, RandomListNode> map=new HashMap<RandomListNode, RandomListNode>();
RandomListNode cur=pHead;
while(cur!=null){
map.put(cur, new RandomListNode(cur.label));
cur=cur.next;
}
cur=pHead;
while(cur!=null){
map.get(cur).next=map.get(cur.next);
map.get(cur).random=map.get(cur.random);
cur=cur.next;
}
return map.get(pHead);
}
}
//方法二
遍历一次链表,将链表复制的副本节点放到自己后面,再从左到右遍历一次链表,设置random指针。分离链表,返回。
package com.chen.zaixian.array;
import java.util.HashMap;
public RandomListNode Clone(RandomListNode pHead) {
if(pHead==null){return null;}
RandomListNode cur=pHead;
RandomListNode next=null;
while(cur!=null){
next=cur.next;
cur.next=new RandomListNode(cur.label);
cur.next.next=next;
cur=next;
}
cur=pHead;
RandomListNode curCopy=null;
while(cur!=null){
next=cur.next.next;
curCopy=cur.next;
curCopy.random=cur.random!=null?cur.random.next:null;
cur=next;
}
RandomListNode res=pHead.next;
cur=pHead;
while(cur!=null){
next=cur.next.next;
curCopy=cur.next;
cur.next=next;
curCopy.next=next!=null?next.next:null;
cur=next;
}
return res;
}
0 0
- 复杂链表的复制(复制含有随机指针节点的链表)
- 复制含有随机指针节点的链表
- 如何复制一个含有随机指针节点的链表
- 复制含有随机指针节点的链表
- 复制含有随机节点的链表
- 复制含有随机指针的链表
- 链表问题---复制含有随机指针节点的链表
- 链表问题——复制含有随机指针节点的链表
- 复制含有随机指针节点的链表——C++实现
- 复杂链表的复制(结点包含随机指针)
- LintCode(M) 复制带随机指针的复杂链表
- 含有random指针的链表复制
- LeetCode OJ 之 Copy List with Random Pointer(复制含有随机指针的链表)
- 复制带随机指针的链表
- 复制带随机指针的链表
- 复制带随机指针的链表
- 复制带随机指针的链表
- 复制带随机指针的链表
- memcpy的函数
- javaweb三大组件之Filter(一)
- 工作流Activiti的学习总结(四)Spring和Activiti的整合配置讲解
- 读书笔记-数论
- BZOJ 1036: [ZJOI2008]树的统计Count
- 复杂链表的复制(复制含有随机指针节点的链表)
- Android开发之如何保证Service不被杀掉 这只是介绍少走弯路 必须用C/jni 实现守护进程 java是无法实现的
- oracle clob转成java String
- delphi带包编译详解 build with runtime package
- 自定义View实现单击,双击效果
- backbone+SUI+组件化开发,移动开发例子
- AndroidStudio 中如何导入和删除jar包
- ServletContext的讲解
- 自定义View之仿淘宝详情页