[LeetCode]138. Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

复制复杂链表,每个节点有一个random属性随机指向一个任意节点

解法一:

遍历原链表,复制random以外的所有属性,建立原链表和复制链表每个节点的映射,第二部根据字典映射设置每个节点的random

注意映射的字典中要有None:None,不然无法AC

看完评论区别人的代码,再看自己写的代码完全不忍直视。。。。。。。。。。。。。。。。。。。。

 1 class Solution(object):
 2     def copyRandomList(self, head):
 3         """
 4         :type head: RandomListNode
 5         :rtype: RandomListNode
 6         """
 7         tmphead = head
 8         pre = None
 9         d = {}
10         d[None]=None
11         res = None
12         while tmphead:
13             tmp = RandomListNode(tmphead.label)
14             d[tmphead] = tmp
15             if pre == None:
16                 pre = res = tmp
17             else:
18                 pre.next = tmp
19                 pre = tmp
20             tmphead = tmphead.next
21         tmphead = head
22         tmpres = res
23         while tmphead:
24             tmpres.random = d[tmphead.random]
25             tmpres = tmpres.next
26             tmphead = tmphead.next
27         return res
28         

解法二:

1.在每个节点后面加入一个一样的节点

2.设置每个节点的random

3.分离两个链表

 下面的代码有bug,但是没找出来,先放这吧

 1 class Solution(object):
 2     def copyRandomList(self, head):
 3         """
 4         :type head: RandomListNode
 5         :rtype: RandomListNode
 6         """
 7         tmphead = head
 8         while tmphead:
 9             tmp = RandomListNode(tmphead.label)
10             node = tmphead.next
11             tmphead.next = tmp
12             tmp.next = node
13             tmphead = node
14         tmphead = head
15         while tmphead:
16             if tmphead.random:
17                 tmphead.next.random = tmphead.random.next
18             tmphead = tmphead.next.next
19         tmphead = head
20         res = None
21         ptr = None
22         while tmphead:
23             if res == None:
24                 res = tmphead.next
25                 ptr = res
26             else:
27                 ptr.next = tmphead.next
28             tmphead.next=ptr.next
29             tmphead = tmphead.next
30         return res
原文地址:https://www.cnblogs.com/fcyworld/p/6502929.html