题目:
实现函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 sibling 指针指向链表中的任意节点或者 null 。
分析一:
分三步:先复制next,在复制sibling, 最后拆开。
代码一:
package offer.xzs.thirty2thirtynine.thirtyfive;
public class Demo01 {
public static void main(String[] args) {
ComplexListNode head = new ComplexListNode(1);
ComplexListNode node1 = new ComplexListNode(2);
ComplexListNode node2 = new ComplexListNode(3);
ComplexListNode node3 = new ComplexListNode(4);
ComplexListNode node4 = new ComplexListNode(5);
head.setNext(node1);
head.setSibling(node2);
node1.setNext(node2);
node1.setSibling(node4);
node2.setNext(node3);
node2.setSibling(null);
node3.setNext(node4);
node3.setSibling(node1);
node4.setNext(null);
node4.setSibling(null);
ComplexListNode complexListNode = nodeClone(head);
System.out.println(complexListNode);
}
public static ComplexListNode nodeClone(ComplexListNode head) {
if (head == null) {
return head;
}
ComplexListNode cur = head;
while (cur != null) {
ComplexListNode newNode1 = new ComplexListNode(cur.getValue());
newNode1.setNext(cur.getNext());
cur.setNext(newNode1);
cur = newNode1.getNext();
}
cur = head;
while (cur != null) {
ComplexListNode newNode2 = cur.getNext();
if (cur.getSibling() != null) {
newNode2.setSibling(cur.getSibling().getNext());
}
cur = newNode2.getNext();
}
cur = head;
ComplexListNode pHead = head.getNext();
while (cur.getNext() != null) {
ComplexListNode newNode3 = cur.getNext();
cur.setNext(newNode3.getNext());
cur = newNode3;
}
return pHead;
}
}