您的位置:首页 > Web前端

剑指offer: 复杂链表的复制

2017-03-18 18:32 429 查看
题目:

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)

思路:

1.不考虑随机指针,复制节点并插入其后方位置

2.用两个指针同时遍历,复制随机指针

3.借助一个节点变量,将链表拆成两个

代码:

/*
public class RandomListNode
{
public int label;
public RandomListNode next, random;
public RandomListNode (int x)
{
this.label = x;
}
}*/
class Solution
{
public RandomListNode Clone(RandomListNode pHead)
{
// write code here
if(pHead == null)
return null;
RandomListNode cur = pHead;
while(cur != null)
{
RandomListNode node = new RandomListNode(cur.label);
node.next = cur.next;
cur.next = node;
cur = node.next;
}
cur = pHead;
while(cur != null)
{
RandomListNode next = cur.next;
if(cur.random != null)
{
next.random = cur.random.next;
}
cur = next.next;
}
cur = pHead;
RandomListNode newHead = cur.next;
while(cur.next != null)
{
RandomListNode temp = cur.next;
cur.next = temp.next;
cur = temp;
}
return newHead;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: