复杂链表的复制(剑指offer 面试题26)
2020-02-26 本文已影响0人
抬头挺胸才算活着
import lombok.Data;
@Data
public class ComplexListNode {
private int value;
private ComplexListNode next;
private ComplexListNode siblingNode;
public ComplexListNode() {
}
public ComplexListNode(int value) {
this.value = value;
}
public ComplexListNode(int value, ComplexListNode next) {
this.value = value;
this.next = next;
}
public static ComplexListNode myClone(ComplexListNode head) {
if(head==null)
return null;
cloneDouble(head);
cloneSibling(head);
return seperateDouble(head);
}
private static void cloneDouble(ComplexListNode head) {
ComplexListNode node = head;
while(node!=null) {
ComplexListNode newNode = new ComplexListNode();
newNode.setValue(node.getValue());
newNode.setNext(node.next);
node.setNext(newNode);
node = newNode.getNext();
}
}
private static void cloneSibling(ComplexListNode head) {
ComplexListNode node = head;
while(node!=null) {
ComplexListNode newNode = node.getNext();
ComplexListNode siblingNode = node.getSiblingNode();
if(siblingNode==null) {
newNode.setSiblingNode(null);
} else {
newNode.setSiblingNode(siblingNode.getNext());
}
node = newNode.getNext();
}
}
private static ComplexListNode seperateDouble(ComplexListNode head) {
ComplexListNode newHead = head.getNext();
ComplexListNode node = head;
while(node!=null) {
ComplexListNode nextNode = node.getNext();
ComplexListNode next2Node = nextNode.getNext();
ComplexListNode next3Node = next2Node==null?null:next2Node.getNext();
node.setNext(next2Node);
nextNode.setNext(next3Node);
node=next2Node;
}
return newHead;
}
public static void traversal(ComplexListNode head){
while (head!=null) {
System.out.println("this node value is: " + head.value);
if(head.getSiblingNode()==null) {
System.out.println("this node's sibling value is: null" );
} else {
System.out.println("this node's sibling value is: " + head.getSiblingNode().getValue());
}
head = head.next;
}
}
}