-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopyListwithRandomPointer.py
More file actions
36 lines (33 loc) · 954 Bytes
/
copyListwithRandomPointer.py
File metadata and controls
36 lines (33 loc) · 954 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/copy-list-with-random-pointer/
# Author: Miao Zhang
# Date: 2021-01-21
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head:
return None
nodedict = {}
dummy = Node(0, None, None)
newhead = dummy
tmp = head
while tmp:
node = Node(tmp.val, tmp.next, None)
nodedict[tmp] = node
newhead.next = node
tmp = tmp.next
newhead = newhead.next
tmp = head
while tmp:
if tmp.random:
nodedict[tmp].random = nodedict[tmp.random]
tmp = tmp.next
return dummy.next