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; } }
复制含有随机指针节点的链表
最新推荐文章于 2023-08-05 17:49:57 发布