zoukankan      html  css  js  c++  java
  • [leetcode]Copy List with Random Pointer @ Python

    原题地址:https://oj.leetcode.com/problems/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.

    解题思路:这题主要是需要深拷贝。看图就明白怎么写程序了。

    第一步,在原链表的每个节点后面都插入一个新节点,新节点的内容和前面的节点一样。比如上图,1后面插入1,2后面插入2,依次类推。

    第二步,原链表中的random指针如何映射呢?比如上图中,1节点的random指针指向3,4节点的random指针指向2。如果有一个tmp指针指向1(蓝色),则一条语句:tmp.next.random = tmp.random.next;就可以解决这个问题。

    第三步,将新的链表从上图这样的链表中拆分出来。

    代码:

    # 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:
        # @param head, a RandomListNode
        # @return a RandomListNode
        def copyRandomList(self, head):
            #http://www.cnblogs.com/zuoyuan/p/3745126.html
            if head == None: return None
            # Step 1: duplicate nodes in order
            tmp = head
            while tmp:
                newNode = RandomListNode(tmp.label)
                newNode.next = tmp.next
                tmp.next = newNode
                tmp = tmp.next.next
            # Step 2: preseve random pointer
            tmp = head
            while tmp:
                if tmp.random:
                    tmp.next.random = tmp.random.next  # assign the old node's random pointer to new duplicated node's random filed
                tmp = tmp.next.next
            # Step 3: extract new list and return
            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

    参考:

    http://www.cnblogs.com/zuoyuan/p/3745126.html

  • 相关阅读:
    go语言学习-接口
    go语言学习-函数
    go语言学习-常用命令
    go语言学习-数组-切片-map
    go语言学习-基础知识
    go语言学习-安装和配置
    python套接字基本使用
    debian 10 firewall-cmd --reload 报错
    synchronized 关键字
    Filebeat+Kafka+Logstash+ElasticSearch+Kibana 日志采集方案
  • 原文地址:https://www.cnblogs.com/asrman/p/4194954.html
Copyright © 2011-2022 走看看