leetcode 【 Copy List with Random Pointer 】 python 实现
2024-09-02 04:15:31
题目:
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.
代码:Runtime: 215 ms
# 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):
if head is None:
return head # insert newnode between every two nodes between oldlist
p = head
while p is not None:
newnode = RandomListNode(p.label)
tmp = p.next
p.next = newnode
newnode.next = tmp
p = tmp # copy random point
p = head
while p is not None:
if p.random is not None:
p.next.random = p.random.next
p = p.next.next # extract the new list from mixed list
newhead = head.next
p = head
while p is not None:
tmp = p.next
p.next = p.next.next
p = p.next
if tmp.next:
tmp.next = tmp.next.next
tmp = tmp.next return newhead
思路:
自己想不出来巧的方法 网上找个靠谱的帖子:
参照上述帖子的思路写的python代码。
遇到的一个问题是,一开始判断极端case的时候有“if head.next is None: return head”
结果一直报错,后来去掉后AC了。注意一个点的时候也要复制。
还有就是,一直对python里面变量间的赋值不太清楚,google了一篇如下的日志,讲的比较靠谱一些。
http://www.cnblogs.com/evening/archive/2012/04/11/2442788.html
最新文章
- HDU 4569 Special equations(取模)
- jQuery插件 -- 动态事件绑定插件jquery.livequery.js
- Uva 11988 Broken Keyboard
- 20145308刘昊阳 《Java程序设计》实验五报告
- Lua学习笔记(一):搭建开发环境
- js原生bind()用法[注意不是jquery里面的bind()]
- POJ1159 - Palindrome(区间DP)
- asp.net mvc4 signalR后台自推送
- 走进C++程序世界-----函数相关(全局变量)
- ocp11g培训内部教材_051课堂笔记(047)_SQL
- 一些javascript常用方法
- java.util.ConcurrentModificationException异常排查
- luogu1484 种树 (优先队列)
- mvc 母版页保持不刷新
- Codeforces 998D. Roman Digits 【打表找规律】
- PyCharm 2017.2.3 版本在2017年9月7日发布,支持 Docker Compose
- 第一个spring boot 程序
- Python接口自动化--requests 2
- iOS 基础
- Windows环境下,从零开始搭建Nodejs+Express+Ejs框架(二)---安装Express,ejs
热门文章
- Eucalyptus简介
- [Rails学习之路]初识Ruby(一)
- [VC]VC实现开机自动运行程序
- hdu-1179 Ollivanders: Makers of Fine Wands since 382 BC.---二分图匹配模板
- 【BZOJ2006】[NOI2010] 超级钢琴(堆+RMQ)
- spring-boot自定义启动端口
- angular4 学习日志(一 依赖注入)
- Java基础面试题:String 和StringBuffer的区别
- 问题003:JDK文件夹下的bin有什么作用?javac.exe和java.exe双击后为什么一闪而过,没了?
- 洛谷P1164小A点菜