題目:輸入一個(gè)復(fù)雜鏈表(每個(gè)節(jié)點(diǎn)中有節(jié)點(diǎn)值,以及兩個(gè)指針,一個(gè)指向下一個(gè)節(jié)點(diǎn),另一個(gè)特殊指針指向任意一個(gè)節(jié)點(diǎn)),返回結(jié)果為復(fù)制后復(fù)雜鏈表的head。
練習(xí)地址
https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba
https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/
參考答案
/*
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;
}
cloneNodes(pHead);
connectRandomNodes(pHead);
return reconnectNodes(pHead);
}
private void cloneNodes(RandomListNode head) {
// 根據(jù)原始鏈表的每個(gè)節(jié)點(diǎn) N 創(chuàng)建對(duì)應(yīng)的 N'
RandomListNode node = head;
while (node != null) {
RandomListNode cloned = new RandomListNode(node.label);
cloned.next = node.next;
node.next = cloned;
node = cloned.next;
}
}
private void connectRandomNodes(RandomListNode head) {
// 設(shè)置復(fù)制出來的節(jié)點(diǎn)的 random
RandomListNode node = head, cloned;
while (node != null) {
cloned = node.next;
if (node.random != null) {
cloned.random = node.random.next;
}
node = cloned.next;
}
}
private RandomListNode reconnectNodes(RandomListNode head) {
// 把這個(gè)長(zhǎng)鏈表拆分成兩個(gè)鏈表
RandomListNode node = head, clonedHead = head.next, cloned;
while (node != null) {
cloned = node.next;
node.next = cloned.next;
if (node.next != null) {
cloned.next = node.next.next;
}
node = node.next;
}
return clonedHead;
}
}
復(fù)雜度分析
- 時(shí)間復(fù)雜度:O(n)。
- 空間復(fù)雜度:O(1)。