zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 11

    Copy List with Random Pointer

    思路很容易理解,这题连接完了cur.next是永远存在的,所以copy random link的时候不用特殊处理。break因为一轮包括4个结点,另外在list结尾有特殊情况,所以比较复杂

    • 顺序:以当前(cur)和下一个(被copy结点)为中心,去连接这两个的next,然后只需要沿cur.next推进就可以
    • 特殊情况:因为被copy结点的next是null,不能连接其下下个结点。所以最后一个copy.next是no-op即可
    # Definition for singly-linked list with a random pointer.
    # class RandomListNode(object):
    #     def __init__(self, x):
    #         self.label = x
    #         self.next = None
    #         self.random = None
    
    class Solution(object):
        def copyRandomList(self, head):
            """
            :type head: RandomListNode
            :rtype: RandomListNode
            """
            if not head: return None
            cur = head
            while cur:
                next = cur.next
                cur.next = RandomListNode(cur.label)
                cur.next.next = next
                cur = next
            
            cur = head
            while cur:
                if cur.random:
                    cur.next.random = cur.random.next
                cur = cur.next.next
            
            cur = head
            newH = head.next
            while cur:
                copy = cur.next
                cur.next = copy.next
                if cur.next:
                    copy.next = cur.next.next
                cur=cur.next
            return newH
    
  • 相关阅读:
    Linux 配置 nginx + php
    Laravel 网站项目目录结构规划
    配置服务器 Ubuntu 记录+踩坑
    JavaScript 单例,Hash,抛异常
    易理解版八皇后
    获取bing每日图片
    OpenGL 学习笔记 01 环境配置
    [瞎JB写] C++多态
    c++ initialize_list
    最长上升子序列的二分优化
  • 原文地址:https://www.cnblogs.com/absolute/p/5675799.html
Copyright © 2011-2022 走看看