这是《Google等公司数据结构+算法面试》上的一道题,原题如下:
下图是一个含有5个结点的该类型复杂链表。
图中实线箭头表示m_pNext指针,虚线箭头表示m_pSibling指针。为简单起见,
指向NULL的指针没有画出。
请完成函数ComplexNode*Clone(ComplexNode* pHead),以复制一个复杂链表。
分析:在常见的数据结构上稍加变化,这是一种很新颖的面试题。
要在不到一个小时的时间里解决这种类型的题目,我们需要较快的反应能力,
对数据结构透彻的理解以及扎实的编程功底。
在看到这题时,我首先想到的是先复制m_pNext指针时间为O(n),然后对每个m_pSibling进行遍历搜索并复制时间复杂度为O(n^2)。在参考了网上提供的思路之后,自己写了段代码实现了一下。
源码:
public class ComplexList {
static class ComplexNode {
public ComplexNode(int value) {
this.value = value;
}
int value;
ComplexNode next;
ComplexNode sibling;
}
public static ComplexNode clone(ComplexNode head) {
if (head == null) {
return null;
}
ComplexNode p = head;
//在每个原节点后复制一个新节点
while (p != null) {
ComplexNode temp = new ComplexNode(p.value);
temp.next = p.next;
p.next = temp;
p = temp.next;
}
ComplexNode q;
p = head;
//更新新节点的sibling值
while (p != null) {
q = p.next;
if (p.sibling != null)
q.sibling = p.sibling.next;
p = p.next.next;
}
p = head;
ComplexNode newHeadNode = head.next;
//将链表拆分为原链表和新链表
while (p != null) {
q = p.next;
p.next = q.next;
if (q.next != null)
q.next = q.next.next;
p = p.next;
}
return newHeadNode;
}
public static void main(String[] args) {
ComplexNode n1 = new ComplexNode(2);
ComplexNode n2 = new ComplexNode(3);
ComplexNode n3 = new ComplexNode(4);
ComplexNode n4 = new ComplexNode(5);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n1.sibling = n2;
n2.sibling = n4;
n3.sibling = n2;
n4.sibling = n1;
ComplexNode newNode = clone(n1);
ComplexNode p = newNode;
while (p != null) {
System.out.print(p.value+" ");
p = p.next;
}
System.out.println();
}
}