Leetcode 138
思路:使用hashmap,构建对应关系。可以判断是否为循环链表。
# 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 head is None:
return head
new_head = RandomListNode(head.label)
node_map = {}
node1 = head
node2 = new_head
while node1.next is not None:
#此处加一个判断条件,可判断是否为循环链表
if node_map[node1] is not None:
break
node_map[node1] = node2
node1 = node1.next
node2.next = RandomListNode(node1.label)
node2 = node2.next
node_map[node1] = node2
node1 = head
node2 = new_head
while node1.next is not None:
if node1.random is not None:
node2.random = node_map[node1.random]
node1 = node1.next
node2 = node2.next
if node1.random is not None:
node2.random = node_map[node1.random]
return new_head