/**
* 複雜鏈表的複製
*
* @param root
* @return
*/
public ComplexListNode clone(ComplexListNode root) {
//複製節點並拼接到後面
cloneNodes(root);
//複製sibling節點
connectSibNode(root);
//斷開節點
ComplexListNode res = reconnectNodes(root);
return res;
}
/**
* 複製節點並拼接到後面
*
* @param root
*/
private void cloneNodes(ComplexListNode root) {
ComplexListNode head = root;
while (head != null) {
ComplexListNode clone = new ComplexListNode(head.v);
clone.next = head.next;
head.next = clone;
head = clone.next;
}
}
/**
* 複製sibling節點
*
* @param root
*/
private void connectSibNode(ComplexListNode root) {
ComplexListNode head = root;
while (head != null) {
ComplexListNode cloneSibling = head.next;
if (null != head.sibling) {
cloneSibling.sibling = head.sibling.next;
}
head = cloneSibling.next;
}
}
/**
* 斷開節點
*
* @param root
* @return
*/
private ComplexListNode reconnectNodes(ComplexListNode root) {
ComplexListNode head = root;
ComplexListNode dummy = new ComplexListNode(-1);
ComplexListNode cur = dummy;
while (head != null) {
cur.next = head.next;
cur = cur.next;
head.next = cur.next;
head = head.next;
}
return dummy.next;
}
/**
* 複雜鏈表的複製
*
* @param root
* @return
*/
public ComplexListNode clone1(ComplexListNode root) {
ComplexListNode head = root;
Map<ComplexListNode, ComplexListNode> map = new HashMap<>();
ComplexListNode dummy = new ComplexListNode(-1);
ComplexListNode cur = dummy;
while (head != null) {
ComplexListNode next = new ComplexListNode(head.v);
cur.next = next;
cur = cur.next;
map.put(head, cur);
head = head.next;
}
head = root;
while (head != null) {
ComplexListNode complexListNode = map.get(head.sibling);
map.get(head).sibling = complexListNode;
head = head.next;
}
return dummy.next;
}
劍指Offer學習-面試題35:複雜鏈表的複製
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.