题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
题解一
利用map实现
import java.util.Map;
import java.util.HashMap;
/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
if(pHead == null) {
return null;
}
Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
RandomListNode newHead = new RandomListNode(pHead.label);
RandomListNode cur = pHead;
RandomListNode newCur = newHead;
map.put(cur, newCur);
while(cur != null) {
if(cur.next != null) {
if(!map.containsKey(cur.next))
map.put(cur.next, new RandomListNode(cur.next.label));
newCur.next = map.get(cur.next);
}
if(cur.random != null) {
if(!map.containsKey(cur.random)) {
map.put(cur.random, new RandomListNode(cur.random.label));
}
newCur.random = map.get(cur.random);
}
cur = cur.next;
newCur = newCur.next;
}
return newHead;
}
}
题解二
首先复制每个结点,并插入到原链表当中,完成next引用的复制;
其次遍历链表完成random引用的复制;
最后分离链表;
/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
if(pHead == null)
return null;
RandomListNode cur = pHead;
while(cur != null) {
RandomListNode temp = new RandomListNode(cur.label);
temp.next = cur.next;
cur.next = temp;
cur = cur.next.next;
}
cur = pHead;
while(cur != null) {
if(cur.random == null)
cur.next.random = null;
else
cur.next.random = cur.random.next;
cur = cur.next.next;
}
cur = pHead;
RandomListNode newHead = pHead.next;
RandomListNode newCur = newHead;
while(cur != null) {
cur.next = newCur.next;
cur = cur.next;
if(newCur.next != null)
newCur.next = newCur.next.next;
newCur = newCur.next;
}
return newHead;
}
}