題目描述:
輸入一個複雜鏈表(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),返回結果爲複製後複雜鏈表的head。(注意,輸出結果中請不要返回參數中的節點引用,否則判題程序會直接返回空)
思路:
- 複製並插入:複製舊鏈表的每個結點,如:複製A得到A1,將A1插入A的後面;
- 遍歷鏈表,補充新結點的 random 域,如:A1.random = A.random.next;
- 拆分:將鏈表分成原鏈表和複製後的鏈表。
具體代碼如下:
/*
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 oldCur = pHead;
//1.複製並插入
while(oldCur != null){
RandomListNode newNode = new RandomListNode(oldCur.label);
newNode.next = oldCur.next;
oldCur.next = newNode;
oldCur = newNode.next;
}
oldCur = pHead;
//2.修改新鏈表的random域
while(oldCur != null){
RandomListNode newCur = oldCur.next;
if(oldCur.random != null) {
newCur.random = oldCur.random.next;
}
oldCur = newCur.next;
}
//3.拆分
oldCur = pHead;
RandomListNode res = pHead.next;
RandomListNode tmp = oldCur.next;
while(oldCur.next != null){
oldCur.next = tmp.next;
oldCur = tmp;
tmp = tmp.next;
}
return res;
}
}