【leetcode】138. Copy List with Random Pointer
题目如下:
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.
Example 1:
Input: {"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1} Explanation: Node 1's value is 1, both of its next and random pointer points to Node 2. Node 2's value is 2, its next pointer points to null and its random pointer points to itself.
Note:
- You must return the copy of the given head as a reference to the cloned list.
解题思路:我的方法是先深拷贝list及其next,同时把新旧两个list的每个元素浅拷贝都存起来放到两个数组中;第二次再遍历旧的list,根据random找到对应item在数组中的下标,再把新的list中同一个item指向数组中对应的下标的元素即可。
代码如下:
""" # Definition for a Node. class Node(object): def __init__(self, val, next, random): self.val = val self.next = next self.random = random """ class Solution(object): def copyRandomList(self, head): """ :type head: Node :rtype: Node """ list1 = [] list2 = [] new_head = None current = None old_head = head while old_head is not None: if new_head == None: new_head = Node(old_head.val,None,None) current = new_head else: new_node = Node(old_head.val,None,None) current.next = new_node current = current.next list1.append(old_head) list2.append(current) old_head = old_head.next old_head = head current = new_head while old_head is not None: if old_head.random is not None: inx = list1.index(old_head.random) current.random = list2[inx] old_head = old_head.next current = current.next return new_head