LintCode(105) 复制带随机指针的链表
2016-06-07 21:44
411 查看
题目
复制带随机指针的链表
给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。返回一个深拷贝的链表。
分析
一个经典题目,思想就是在复制每个原节点链接其后,然后依次添加新节点的random指针。遍历复制后的链表,删除原节点。
就不详述了,看代码,重点是练习Python实现~~~
Python代码
# 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): # write your code here if head is None: return None p = head while p is not None: r = p.next node = RandomListNode(p.label) node.next = p.next p.next = node p = r p = head q = p.next if q is None: print("None") while p is not None and q is not None: if p.random is not None: q.random = p.random.next p = q.next if p is not None: q = p.next ret = head.next del head q = ret while q.next is not None: p = q.next q.next = p.next del p q = q.next return ret
GitHub -- Python完整代码
C++代码
/** * Definition for singly-linked list with a random pointer. * struct RandomListNode { * int label; * RandomListNode *next, *random; * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} * }; */ class Solution { public: /** * @param head: The head of linked list with a random pointer. * @return: A new head of a deep copy of the list. */ RandomListNode *copyRandomList(RandomListNode *head) { // write your code here if(head == NULL) { return NULL; }//if RandomListNode *p = head; while(p != NULL) { RandomListNode *r = p->next; RandomListNode *tmp = new RandomListNode(p->label); tmp->next = p->next; p->next = tmp; p = r; }//while p = head; RandomListNode *q = head->next; while(p && q) { if(p->random) { q->random = p->random->next; } p = q->next; if(p) { q = p->next; } }//while RandomListNode *ret = head->next; delete head; q = ret; while(q->next) { p = q->next; q->next = p->next; delete p; q = q->next; }//while return ret; } };
GitHub -- C++代码
相关文章推荐
- intellij的maven工程"Server IPC version 9 cannot communicate with client version"错误的解决办法
- 拾遗系列(三)屏幕适配:Autolayout
- vc中动态设置属性页字体
- CasperJS基于PhantomJS抓取页面
- 站立会议07(第二期)
- 第3章 正则表达式1
- C/C++ 完全数
- 【转】【复】实现复数中的运算符重载
- 在web.xml中配置diaplay-name是什么意思
- 使用C#写出一个简单的记事本程序
- Android知识-ViewPager中嵌套activity页面
- 2969 角谷猜想
- oop概念性讲解
- 动态规划1-数字三角形(算法基础 第4周)
- Ansible源码分析之svn模块
- Android5.X和Android6.X上读写外置 USB设备的方案
- CS231n 2016 通关 第五、六章 Batch Normalization 作业
- emoji
- Leetcode Binary Tree Upside Down
- C/C++ 中缀表达式转换成后缀表达式并求值