链表的深度复制

链表的经典题目
##题目:有一个链表,每个结点有两个引用,一个引用是指向下一个结点的 next引 用,一个是指向随意位置的random引用。要求将这个链表完整的复制成一个新的链表
思路:
1、复制原链表的每一个结点,让新的结点插入到原链表的当前结点的下一个位置
例如:原链表:3–>9–>4–>8–>6–>null
复制后的链表:3–>3–>9–>9–>4–>4–>8–>8–>6–>6–>null
2、定义两个引用,分别指向元结点和新节点,复制每一个结点的random
3、最后把链表拆分开来,返回复制后的链表
源代码:
static CNode copy(CNode head)
{
if (head==null)
{
return null;
}
CNode p1=head;
//复制简单链表
while(p1!=null)
{
CNode p2=new CNode(p1.val);
p2.next=p1.next;
p1.next=p2;
p1=p2.next;
}
//复制rendom
p1=head;
while(p1!=null)
{
CNode p2=p1.next;
if(p1.random!=null)
{
p2.random=p1.random.next;
}
p1=p2.next;
}
//拆分链表
p1=head;
CNode newhHead=head.next;
while(p1!=null)
{
CNode p2=p1.next;
p1.next=p2.next;
if(p2.next!=null)
{
p2=p2.next.next;
}
p1=p2.next;
}
return newhHead;
}

你可能感兴趣的:(java,链表)