题目描述
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
思路:
先新建copy节点插入到每一个节点后,然后遍历复制random指针,最后将两个链表拆分开,注意插入后步长为2,细心点就好。
代码:
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) return null;
// 添加新节点到旧节点后面
RandomListNode cur = head;
while (cur != null){
insertNode(cur);
cur = cur.next.next;
}
// 设置random指针
cur = head;
while (cur != null){
if (cur.random != null){
cur.next.random = cur.random.next;
}
else {
cur.next.random = null;
}
cur = cur.next.next;
}
// 取下新节点
cur = head;
RandomListNode newHead = head.next;
while (cur != null){
divideNode(cur);
cur = cur.next;
}
return newHead;
}
private void insertNode(RandomListNode cur){
RandomListNode newNode = new RandomListNode(cur.label);
newNode.next = cur.next;
cur.next = newNode;
}
private void divideNode(RandomListNode cur){
RandomListNode newCur = cur.next;
cur.next = newCur.next;
if (newCur.next != null){
newCur.next = newCur.next.next;
}
}
}
网友评论