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

LeetCode Copy List with Random Pointer

2014-09-01 22:51 330 查看
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.

题目意思是复制一个节点带有随机指针的链表。

方法是先把链表放入LIST内,然后遍历list为每个节点添加随机指针。

/**
* 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;
}
ArrayList<RandomListNode> oldList=new ArrayList<>();
ArrayList<RandomListNode> newList=new ArrayList<>();
int indexRandom;
RandomListNode tempNode=head;
while (tempNode!=null) {
oldList.add(tempNode);
newList.add(new RandomListNode(tempNode.label));
tempNode=tempNode.next;
}
for (int i = 0; i < oldList.size(); i++) {
if (i<oldList.size()-1) {
newList.get(i).next=newList.get(i+1);
}
indexRandom=oldList.indexOf(oldList.get(i).random);
if (indexRandom>=0) {
newList.get(i).random=newList.get(indexRandom);
}
}

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