leetcode: Copy List with Random Pointer
来源:互联网 发布:比蓝墨云班好用的软件 编辑:程序博客网 时间:2024/05/24 23:14
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.
/*
* 复杂链表表示:存在2个指针,一个指针之后下一个节点,另外一个随机指针指向随机节点
* 分成3步:
* 1. 复制节点,如A-B-C 变成 A-A’-B-B’-C-C’
* 2. 依次遍历节点A,B,C,将这些节点的随机指针与A’B’C’一致
* 3. 分离A-B-C和A’B’C’,A’B’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: RandomListNode *copyRandomList(RandomListNode *head) { if (!head) return nullptr; RandomListNode *p = head, *q = head->next, *newNode = NULL; //step 1 while (p != NULL) { newNode = new RandomListNode(0); newNode->next = p->next; p->next = newNode; newNode->label = p->label; newNode->random = NULL; p = q; if (q) q = q->next; } //step 2 p = head; q = p->next; while (q != NULL) { if (p->random != NULL) q->random = p->random->next; if (q->next == NULL) break; p = q->next; if (p) q = p->next; } //step 3 newNode = head->next; p = head; q = p->next; while (q != NULL) { p->next = q->next; if (q->next == NULL) break; q->next = p->next->next; p = p->next; q = q->next; } return newNode; }};
0 0
- [leetcode][list] Copy List with Random Pointer
- Leetcode: Copy List with Random Pointer
- LeetCode: Copy List with Random Pointer
- [LeetCode] Copy List with Random Pointer
- [leetcode]Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- leetcode Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- LeetCode题解:Copy List with Random Pointer
- [LeetCode]Copy List with Random Pointer
- leetcode Copy List with Random Pointer
- leetcode-Copy List with Random Pointer
- Leetcode: Copy List with Random Pointer
- LeetCode | Copy List with Random Pointer
- [LeetCode] Copy List with Random Pointer
- LeetCode OJ:Copy List with Random Pointer
- LeetCode(138)Copy List with Random Pointer
- [LeetCode] - Copy List with Random Pointer
- DWZ
- IOS 模拟器 在iPhone5和iPhone5s显示不全,不能全屏显示
- struts2学习笔记(四)拦截器与拦截器栈
- 【leetcode】Sort Colors
- Android布局控件属性
- leetcode: Copy List with Random Pointer
- 【Application】Application是什么鬼?
- 怎么阅读 Android 系统源码
- 关于Qt的MVC
- sql语句的性能优化问题
- QT编译出错 field has incomplete type
- C# Lambda表达式
- Ehcache(02)——ehcache.xml简介
- webView导入html5(滴滴打车)