美文网首页
138. Copy List with Random Point

138. Copy List with Random Point

作者: April63 | 来源:发表于2018-05-17 15:22 被阅读0次

    剑指offer上的题目,三步走 具体的代码我没写到ac,但是思想是书上的,有个博客写的比较好https://www.cnblogs.com/zuoyuan/p/3745126.html
    代码如下:

    # Definition for singly-linked list with a random pointer.
    # class RandomListNode:
    #     def __init__(self, x):
    #         self.label = x
    #         self.next = None
    #         self.random = None
    
    class Solution:
        def copyRandomList(self, head):
            if head == None: return None
            tmp = head
            while tmp:
                newNode = RandomListNode(tmp.label)
                newNode.next = tmp.next
                tmp.next = newNode
                tmp = tmp.next.next
            tmp = head
            while tmp:
                if tmp.random:
                    tmp.next.random = tmp.random.next
                tmp = tmp.next.next
            newhead = head.next
            pold = head
            pnew = newhead
            while pnew.next:
                pold.next = pnew.next
                pold = pold.next
                pnew.next = pold.next
                pnew = pnew.next
            pold.next = None
            pnew.next = None
            return newhead
    

    相关文章

      网友评论

          本文标题:138. Copy List with Random Point

          本文链接:https://www.haomeiwen.com/subject/ymbbdftx.html