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

Copy List With Random Pointer

2015-07-21 15:58 507 查看
使用HashTable

/**
* 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 dummy1 = new RandomListNode(-1);
RandomListNode dummy2 = new RandomListNode(-1);
dummy1.next = head;
RandomListNode ptr1 = dummy1, ptr2 = dummy2;

Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();

while (ptr1.next != null) {
ptr1 = ptr1.next;
ptr2.next = new RandomListNode(ptr1.label);
ptr2 = ptr2.next;
map.put(ptr1, ptr2);
}
ptr2.next = null;

ptr1 = dummy1;
ptr2 = dummy2;
while (ptr1.next != null) {
ptr1 = ptr1.next;
map.get(ptr1).random = map.get(ptr1.random);
}
return dummy2.next;
}
}

不使用HashTable

/**
* 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 ptr = head;
while (ptr != null) {
RandomListNode copy = new RandomListNode(ptr.label);
copy.next = ptr.next;
ptr.next = copy;
ptr = copy.next;
}

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

ptr = head;
RandomListNode newHead = head.next;
while (ptr != null) {
RandomListNode temp = ptr.next;
ptr.next = temp.next;
if (temp.next != null) {
temp.next = temp.next.next;
}
ptr = ptr.next;
}
return newHead;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Hash Table Linked List