Copy List with Random Pointer 复制带随机指针的链表
Description
A linked list of length n
is given such that each node contains an additional random pointer, which could point to any node in the list, or null
.
Construct a deep copy of the list. The deep copy should consist of exactly n
brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next
and random
pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.
For example, if there are two nodes X
and Y
in the original list, where X.random --> Y
, then for the corresponding two nodes x
and y
in the copied list, x.random --> y
.
Return the head of the copied linked list.
The linked list is represented in the input/output as a list of n
nodes. Each node is represented as a pair of [val, random_index]
where:
val
: an integer representingNode.val
random_index
: the index of the node (range from0
ton-1
) that therandom
pointer points to, ornull
if it does not point to any node.
Your code will only be given the head
of the original linked list.
将一个链表,按照给定的x值,分成2部分,链表前部小于x,后部大于等于x
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
思路:
将每个节点都复制一份并插入在原始节点之后,所有random指向原始节点,将复制出的节点中的random指向原始节点的后一个。最后将复制的节点两两拆开。
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
if (head==null){
return null;
}
Node p = head;
Node q = null;
while (p!=null){
q = new Node(p.val);
q.random = p.random;
q.next = p.next;
p.next = q;
p = q.next;
}
p = head.next;
while(p!=null){
if (p.random!=null){
p.random = p.random.next;
}
else{
p.random = null;
}
p = p.next;
if (p!=null){
p = p.next;
}
}
Node newhead = head.next;
p = head;
while(p!=null){
q = p.next;
p.next = q.next;
if (p.next!=null){
q.next = p.next.next;
}
p = p.next;
}
return newhead;
}
}