第一题 复杂链表的复制
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的 head。
参考 https://www.cnblogs.com/yingzizzzzzz/p/7015886.html
解题思路:先插入一个复制链表,然后将复制链表的随机指针赋值,然后拆分大的链表,有一个疑惑是拆分
package com.lyc.dataautest;
public class CopyRandomListNode {
public static RandomListNode copy(RandomListNode pHead) {
if (pHead == null)
return null;
// 复制原始链表
RandomListNode current = pHead;
while (current != null) {
RandomListNode pclone = new RandomListNode(current.lable);
pclone.next = current.next;
pclone.random = null;
current.next = pclone;
current = pclone.next;
}
// 设置复制表的random
current = pHead;
while (current != null) {
if (current.random != null) {
// 当前随机节点的下一个节点是,当前随机节点的随机节点的复制,因此将此随机复制节点给与当前节点的下一个节点(即复制节点)
current.next.random = current.random.next;
}
current = current.next.next;
}
// 将长链表分开,克隆的以及原始的
current = pHead;
RandomListNode pcloneHead = pHead.next;
while (current.next != null) {
RandomListNode next = current.next;
current.next = next.next;
current = next;
}
return pcloneHead;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
RandomListNode head = new RandomListNode(1);
RandomListNode b = new RandomListNode(2);
RandomListNode c = new RandomListNode(3);
RandomListNode d = new RandomListNode(4);
RandomListNode e = new RandomListNode(5);
head.next = b;
head.random = c;
b.next = c;
b.random = e;
c.next = d;
c.random = null;
d.next = e;
d.random = b;
e.next = null;
e.random = null;
RandomListNode temp = null;
temp = copy(head);
while (temp != null) {
System.out.println(temp.lable);
temp = temp.next;
}
}
}
class RandomListNode {
int lable;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int lable) {
this.lable = lable;
}
}