复制含有随机指针节点的链表
2017-08-07 22:01
357 查看
import java.util.HashMap; /** * Created by 糖糖 on 2017/8/7. */ public class copyLink { public static Snode copyLink(Snode head ){ Snode cur = head; HashMap<Snode,Snode> hashMap = new HashMap<Snode,Snode>(); while (cur !=null){ hashMap.put(cur,new Snode(cur.data)); cur = cur.next; } cur = head; while (cur != null){ hashMap.get(cur).next = hashMap.get(cur.next); hashMap.get(cur).rand = hashMap.get(cur.rand); cur = cur.next; } return hashMap.get(head); } public static Snode cpoyLink2(Snode head){ Snode cur = head; Snode next = null; //复制链表 while (cur!=null){ next = cur.next; cur.next = new Snode(cur.data); cur.next.next = next; cur = next; } //复制rand关系 cur = head; Snode curcopy = null; while (cur != null){ next = cur.next.next; curcopy = cur.next; curcopy.rand = cur.rand== null?null:cur.rand; cur = next; } //拆分链表 cur = head; Snode res = head.next; while (cur != null){ next = cur.next.next; curcopy = cur.next; cur.next = next; curcopy.next = next!=null?next:null; cur = next; } return res; } public static void main(String args[]){ Snode s1=new Snode(1); Snode s2=new Snode(2); Snode s3=new Snode(3); s1.next = s2; s2.next = s3; s1.rand = s2; s3.rand = s2; Snode snode = copyLink(s1); Snode snode1 = cpoyLink2(s1); System.out.println(snode.rand.data); System.out.println(snode1.rand.data); } } class Snode{ int data; Snode next; Snode rand; public Snode(int data){ this.data=data; next = null; rand = null; } }
相关文章推荐
- 链表问题---复制含有随机指针节点的链表
- 复制含有随机指针节点的链表
- 链表问题——复制含有随机指针节点的链表
- 如何复制一个含有随机指针节点的链表
- 复杂链表的复制(复制含有随机指针节点的链表)
- 复制含有随机指针节点的链表
- 复制含有随机指针节点的链表——C++实现
- 复制含有随机指针的链表
- 链表含有随机rand指针的复制
- LeetCode OJ 之 Copy List with Random Pointer(复制含有随机指针的链表)
- 一个链表的每个节点,有一个指向next指针指向下一个节点,还有一个rand指针指向这个链表中的一个随机节点或NULL,现在要求复制一个单链表来实现这个链表,返回复制后的新链表。
- O(1)时间复杂度删除链表节点/复制带随机指针的链表
- 复制含有随机节点的链表
- 算法系列之-复制含有随机指针的链表
- 复制带随机指针的链表-LintCode
- 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序
- 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。
- 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序
- [LintCode] 复制带随机指针的链表 Copy List with Random Pointer
- 带随机指针的链表复制问题