题目:
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针random指向一个随机节点),请对此链表进行深拷贝,并返回拷贝后的头结点。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路1-三步法:
- 这道题主要是考察链表指针的操作,在理解题意的前提下分为三步
- 首先要拷贝简单链表的每个结点至原结点的下一个位置(拷贝值)
- 其次要拷贝其中的random指针(拷贝结点的random指针指向原结点random指针的下一个结点),因为就相当于指向了拷贝后的结点
- 最后将前两步生成的长链表拆分出拷贝的部分(即按奇偶分割),因为拷贝random指针时依赖第二步的关联方式,如果直接开辟一个新链表,只能做到浅拷贝,是复制不了其中的random指针的
此处贴个图更形象:
代码1:
public class Solution {
public RandomListNode Clone(RandomListNode pHead) {
if(pHead == null) {
return null;
}
RandomListNode currentNode = pHead;
//1、复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
while(currentNode != null){
RandomListNode cloneNode = new RandomListNode(currentNode.label);
RandomListNode nextNode = currentNode.next;
currentNode.next = cloneNode;
cloneNode.next = nextNode;
currentNode = nextNode;
}
currentNode = pHead;
//2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
while(currentNode != null) {
currentNode.next.random = currentNode.random==null?null:currentNode.random.next;
currentNode = currentNode.next.next;
}
//3、拆分链表,将链表拆分为原链表和复制后的链表
currentNode = pHead;
RandomListNode pCloneHead = pHead.next;
while(currentNode != null) {
RandomListNode cloneNode = currentNode.next;
currentNode.next = cloneNode.next;
cloneNode.next = cloneNode.next==null?null:cloneNode.next.next;
currentNode = currentNode.next;
}
return pCloneHead;
}
}
思路2-Hash法:
- 直接用map来记录指针间的联系,可以直接找到random指针
代码2:
import java.util.HashMap;
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
HashMap<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode cur = pHead;
while (cur != null) {
map.put(cur, new RandomListNode(cur.label));
cur = cur.next;
}
cur = pHead;
while (cur != null) {
map.get(cur).next = map.get(cur.next);
cur = cur.next;
}
RandomListNode resHead = map.get(pHead);
cur = pHead;
while (cur != null) {
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
return resHead;
}
}