Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update code.py #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion 剑指offer/025-复杂链表的复制/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,41 @@ def Clone(pHead):
p.next.next = RandomListNode(3)
p.next.next.next = RandomListNode(4)
p.next.next.next.next = RandomListNode(5)
print(Clone(p))
print(Clone(p))


class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# 深拷贝也可以
# return copy.deepcopy(pHead)

# 复制一个一样的node,并且添加到之前的链表的每一个node后面
if pHead == None:
return None

pTmp = pHead
while pTmp:
node = RandomListNode(pTmp.label)
node.next = pTmp.next
pTmp.next = node
pTmp = node.next #将指针移动到下一个被复制的节点

# 实现新建的node的random的指向
pTmp = pHead
while pTmp:
if pTmp.random:
pTmp.next.random = pTmp.random.next
pTmp = pTmp.next.next

# 断开原来的node和新node的连接
pTmp = pHead
newHead = pHead.next #保存复制链表后的第二个元素的地址
pNewTmp = pHead.next
while pTmp:
pTmp.next = pTmp.next.next
if pNewTmp.next:
pNewTmp.next = pNewTmp.next.next
pNewTmp = pNewTmp.next
pTmp = pTmp.next
return newHead