class Solution {
private static ListNode copyAndMerge(ListNode head) {
ListNode p = head;
ListNode next;
ListNode copy;
while (p != null) {
next = p.next;
copy = new ListNode(p.val + 3);
p.next = copy;
copy.next = next;
p = next;
}
p = head;
while (p != null) {
copy = p.next;
next = copy.next;
if (p.rand != null) {
copy.rand = p.rand.next;
}
p = next;
}
return head;
}
private static ListNode splite(ListNode head) {
if (head == null) {
return null;
}
ListNode p1 = head;
ListNode p2 = head.next, result = p2;
ListNode next;
while (p1 != null) {
next = p1.next.next;
p1.next = next;
p2.next = next == null ? null : next.next;
p1 = p1.next;
p2 = p2.next;
}
return result;
}
private static ListNode function(ListNode head) {
ListNode n = copyAndMerge(head);
return splite(n);
}
private static void print(ListNode head) {
while (head != null) {
System.out.println(head.val);
head = head.next;
}
}
public static void main(String[] args) {
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(3);
// ListNode n4 = new ListNode(5);
// ListNode n5 = new ListNode(1);
n1.next = n2;
n2.next = n3;
n1.rand = n3;
n3.rand = n1;
// n3.next = n4;
// n4.next = n5;
ListNode head = function(n1);
print(head);
}
}
class ListNode {
int val;
ListNode next;
ListNode rand;
ListNode(int x) { val = x; }
}
转载于:https://blog.51cto.com/tianyiya/2334837