您的位置:首页 > 运维架构

[LeetCode] Copy List with Random Pointer

2014-08-19 16:14 316 查看
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.

分三步:

1. 每个节点复制一个新的节点插入该节点后

2. 给所有复制的节点的Random指针赋值,指向被复制节点的random指针所指向的节点的下一个节点(注意判断random指针是否为空)

3. 拆开链表为旧链表和新链表

/**
* 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 newHead = copyAndInsertNode(head);

copyRandomNodes(newHead);
return getNewRandomList(newHead);
}

private RandomListNode getNewRandomList(RandomListNode head) {
RandomListNode pNode = head;
RandomListNode newHead = head.next;
RandomListNode pNewNode = newHead;

while (pNode != null) {
pNode.next = pNewNode.next;
if (pNewNode.next != null) {
pNewNode.next = pNewNode.next.next;
}

pNode = pNode.next;
pNewNode = pNewNode.next;
}

return newHead;
}

private void copyRandomNodes(RandomListNode newHead) {
RandomListNode pNode = newHead;

while (pNode != null) {
if (pNode.random != null) {
pNode.next.random = pNode.random.next;
}

pNode = pNode.next.next;
}
}

private RandomListNode copyAndInsertNode(RandomListNode head) {
RandomListNode pNode = head;

while (pNode != null) {
RandomListNode newNode = new RandomListNode(pNode.label);
newNode.next = pNode.next;
pNode.next = newNode;
pNode = newNode.next;
}

return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java