题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点)。
思路:见剑指offer
代码如下:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
HashMap<RandomListNode,RandomListNode> map = new HashMap<RandomListNode,RandomListNode>();
RandomListNode p = pHead;
RandomListNode q = new RandomListNode(-1);
while(p!=null){
RandomListNode t = new RandomListNode(p.label);
map.put(p, t);
p = p.next;
q.next = t;
q = t;
}
Set<Entry<RandomListNode,RandomListNode>> set = map.entrySet();
Iterator<Entry<RandomListNode,RandomListNode>> it = set.iterator();
while(it.hasNext()){
Entry<RandomListNode, RandomListNode> next = it.next();
next.getValue().random = map.get(next.getKey().random);
}
return map.get(pHead);
}
}
还有一种方法如下:
public class Solution {
public RandomListNode Clone(RandomListNode pHead){
RandomListNode ClonedListNode=null;
RandomListNode newHead=pHead;
if(pHead==null){
return ClonedListNode;
}
ClonedListNode=new RandomListNode(pHead.label);
while(pHead.next!=null){
ClonedListNode.next=pHead.next;
pHead.next=ClonedListNode;
pHead=ClonedListNode.next;
ClonedListNode=new RandomListNode(pHead.label);
}
pHead.next=ClonedListNode;
pHead=newHead;
ClonedListNode=pHead.next;
while(pHead!=null){
if(pHead.random!=null){
ClonedListNode.random=pHead.random.next;
}
pHead=ClonedListNode.next;
if(pHead!=null){
ClonedListNode=pHead.next;
}
}
pHead=newHead;
ClonedListNode=pHead.next;
RandomListNode Clonedhead=pHead.next;
while(pHead!=null){
pHead.next=ClonedListNode.next;
pHead=pHead.next;
if(pHead!=null){
ClonedListNode.next=pHead.next;
ClonedListNode=ClonedListNode.next;
}
}
return Clonedhead;
}
}