Skip to content

Commit 07e1723

Browse files
committed
138
1 parent fdedc76 commit 07e1723

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,7 @@ Success is like pregnancy, Everybody congratulates you but nobody knows how many
3737
|148|[Sort List](https://leetcode.com/problems/sort-list/#/description)| [Python](./linkedlist/sortList.py) | _O(nlogn)_| _O(1)_ | Medium | ||
3838
|61|[Rotate List](https://leetcode.com/problems/rotate-list/#/description)| [Python](./linkedlist/rotateRight.py) | _O(n)_| _O(1)_ | Medium | ||
3939
|19|[Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/#/description)| [Python](./linkedlist/removeNthFromEnd.py) | _O(n)_| _O(1)_ | Medium | ||
40+
41+
42+
## 4/16 Tasks (LinkedList Medium)
43+
|138|[Copy List with Random Pointer](https://leetcode.com/problems/copy-list-with-random-pointer/#/description)| [Python](./linkedlist/copyRandomList.py) | _O(n)_| _O(n)_ | Medium | ||

linkedlist/copyRandomList.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# 138. Copy List with Random Pointer
2+
# Author: Yu Zhou
3+
4+
# 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.
5+
# Return a deep copy of the list
6+
# Definition for singly-linked list with a random pointer.
7+
# class RandomListNode(object):
8+
# def __init__(self, x):
9+
# self.label = x
10+
# self.next = None
11+
# self.random = None
12+
13+
# 思路:
14+
# 这题其实就是拷贝所有的链表到一个新的
15+
# 唯一的难点是如何在拷贝玩所有链表之后,还能够将Random的指针指对
16+
# 所以这里用的方法是用Hash,然后第一次遍历用来建新的Node
17+
# 第二次遍历用来对Hash里面新建的Node进行指针的赋值
18+
19+
class Solution(object):
20+
def copyRandomList(self, head):
21+
"""
22+
:type head: RandomListNode
23+
:rtype: RandomListNode
24+
"""
25+
dic = dict()
26+
m = n = head
27+
28+
#第一次循环用来创建所有原本链表里的Node,并且对他们进行赋值
29+
#需要搞懂的是,这一次循环,新的链表是一个一个单独的Node,他们的指针都还没有赋值
30+
while m:
31+
dic[m] = RandomListNode(m.label)
32+
m = m.next
33+
34+
#第二次循环,用来对这一个一个独立的Node进行他们的指针赋值,其中包括每个链接下一个Node的指针
35+
#以及这道题的另一个Random的指针
36+
while n:
37+
#这里dic[n].next,dic[n]就是key "n" 相对应的val,也就是之前创建的,RandomListNode(m.label)
38+
#然后我们对这个新创建的独立Node,设置他的next pointer
39+
# dic.get(n.next)里面的n.next是reference原List里面的Node的next,不要搞混了
40+
dic[n].next = dic.get(n.next)
41+
dic[n].random = dic.get(n.random)
42+
n = n.next
43+
return dic.get(head)

0 commit comments

Comments
 (0)