边工作边刷题:70天一遍leetcode: day 11
Copy List with Random Pointer
思路很容易理解,这题连接完了cur.next是永远存在的,所以copy random link的时候不用特殊处理。break因为一轮包括4个结点,另外在list结尾有特殊情况,所以比较复杂
- 顺序:以当前(cur)和下一个(被copy结点)为中心,去连接这两个的next,然后只需要沿cur.next推进就可以
- 特殊情况:因为被copy结点的next是null,不能连接其下下个结点。所以最后一个copy.next是no-op即可
# 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
cur = head
while cur:
next = cur.next
cur.next = RandomListNode(cur.label)
cur.next.next = next
cur = next
cur = head
while cur:
if cur.random:
cur.next.random = cur.random.next
cur = cur.next.next
cur = head
newH = head.next
while cur:
copy = cur.next
cur.next = copy.next
if cur.next:
copy.next = cur.next.next
cur=cur.next
return newH