-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopyRandomList.py
More file actions
50 lines (43 loc) · 1.17 KB
/
Copy pathcopyRandomList.py
File metadata and controls
50 lines (43 loc) · 1.17 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# coding=utf-8
"""
@project : algorithmPython
@ide : PyCharm
@file : copyRandomList
@author : illusion
@desc : 138. 复制带随机指针的链表 https://leetcode-cn.com/problems/copy-list-with-random-pointer/
@create : 2021/5/25 1:34 下午:17
"""
# 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 head is None:
return None
cur = head
while cur:
copy_node = Node(cur.val)
tmp, cur.next = cur.next, copy_node
copy_node.next = tmp
cur = tmp
new_head = head.next
cur = head
while cur:
next_node = cur.next
if cur.random:
next_node.random = cur.random.next
cur = next_node.next
if next_node.next:
next_node.next = next_node.next.next
return new_head
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n1.next = n2
n2.next = n3
n2.random = n1
s = Solution()
print(s.copyRandomList(n1))