题目描述:
请实现一个函数复制复杂链表,在复杂链表中,每一个节点除了有一个指向下一个节点的next指针,还有一个指向链表中任意一个节点或为空的p指针;
最好的方法如下:
①把链表的每一个节点都clone一次,并将clone的节点连接在原来相应的节点后面;
②把原来p指针不为空的节点找出来,将对应的clone的节点的p指针指向原节点的p指针指向的节点后面的节点;
③将两个链表拆开;
class ListNode implements Cloneable{
int val;
ListNode next;
ListNode p;
ListNode(int x) {
val = x;
}
public Object clone() {
ListNode listNode = null;
try {
listNode = (ListNode)super.clone();
}catch (Exception e){
e.printStackTrace();
}
return listNode;
}
}
/**
* 复制复杂链表
* @param head
* @return
*/
public static ListNode clone_listnode(ListNode head) {
clone_node(head);
connect_node(head);
return reconnect_node(head);
}
/**
* 把链表的每一个节点都clone一次,并将clone的节点连接在原来相应的节点后面
* @param head
*/
public static void clone_node(ListNode head) {
if(head == null) {
return;
}
ListNode cur = head;
while(cur != null) {
ListNode node = (ListNode) cur.clone();
node.next = cur.next;
cur.next = node;
cur = node.next;
}
}
/**
* 把原来p指针不为空的节点找出来,将对应的clone的节点的p指针指向
* 原节点的p指针指向的节点后面的节点
* @param head
*/
public static void connect_node(ListNode head) {
if(head == null) {
return;
}
ListNode cur = head;
while(cur != null) {
ListNode node = cur.next;
if(cur.p != null) {
node.p = cur.p.next;
}
cur = node.next;
}
}
/**
* 将两个链表拆开
* @param head
* @return
*/
public static ListNode reconnect_node(ListNode head) {
if(head == null) {
return null;
}
ListNode cur = head;
ListNode x = head;
ListNode clone_head = null;
ListNode clone_node = null;
//找头节点
if(cur != null) {
clone_head = clone_node = cur.next;
cur.next = clone_node.next;
cur = cur.next;
x.next = cur;
x = x.next;
}
while(cur != null) {
clone_node.next = cur.next;
clone_node = clone_node.next;
cur.next = clone_node.next;
cur = cur.next;
x.next = cur;
x = x.next;
}
return clone_head;
}
测试代码:
public static void main(String[] args) {
ListNode head = new ListNode(7);
ListNode cur = head;
ListNode sign1 = null,sign2 = null;
for(int i = 1;i < 5;i++) {
cur.next = new ListNode(7+i);
cur = cur.next;
if(i == 2) {
sign1 = cur;
}
if(i == 4) {
sign2 = cur;
}
}
ListNode x = head;
x.p = sign1;
x.next.p = sign2;
show(head);
show(clone_listnode(head));
show(head);
}
/**
* 打印链表
* @param head
*/
public static void show(ListNode head) {
if(head == null) {
return;
}
ListNode cur = head;
while(cur != null) {
System.out.print("\t"+cur.val);
if(cur.p != null) {
System.out.print("p");
}
cur = cur.next;
}
System.out.println();
}
运行结果:
7p 8p 9 10 11
7p 8p 9 10 11
7p 8p 9 10 11