leetcode 138. Copy List with Random Pointer

题目链接:leetcode

思路:
遍历原链表,生成新链表

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
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None

class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if not head:
return None

p = head
newhead = q = RandomListNode(head.label)

while p:
q.next = None if not p.next else RandomListNode(p.next.label)
q.random = None if not p.random else RandomListNode(p.random.label)
p = p.next
q = q.next
return newhead