leetcode Copy List with Random Pointer
来源:互联网 发布:彩票开奖数据 编辑:程序博客网 时间:2024/06/09 20:55
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.
题目大意:对一个单向链表进行深度拷贝,单向链表的每个结点还有一个random指针,或者为NULL,或者指向链表中任意一个结点。
解题思路:
将新结点嵌入对应的结点后面 如old1->new1->old2->new2.....oldn->newn,然后新节点的random指针指向的就是旧结点random指针指向的next
最后恢复原链表,构建新的链表 old->next = old->next->next; new->next = new->next->next;
代码实现如下:
/** * 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 == NULL) return NULL; RandomListNode *iter = head; RandomListNode *newiter, *olditer; //将链表变成old1->new1->old2->new2.....oldn->newn while(iter != NULL) { olditer = iter; iter = iter->next; newiter = new RandomListNode(olditer->label); olditer->next = newiter; newiter->next = iter; } //将新节点的random指针指向新节点的位置 olditer = head; newiter = head->next; while(true) { if(olditer->random == NULL) { newiter->random = NULL; } else { newiter->random = olditer->random->next; } olditer = olditer->next->next; if(olditer == NULL) break; newiter = olditer->next; } //恢复原来的链表 olditer = head; newiter = head->next; iter = newiter; while(true) { olditer->next = newiter->next; olditer = newiter->next; if(olditer == NULL) break; newiter->next = olditer->next; newiter = newiter->next; } return iter; }};
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
- 第01章 概述(1)
- 世界首个万亿富豪或于2039年诞生,怎么回事?
- 用Chrome调试NodeJS
- Median of Two Sorted Arrays 两个有序数组的中位数@LeetCode
- μC/OS-II学习之:任务,信号量、邮箱、队列及其区别
- leetcode Copy List with Random Pointer
- 输入a和b两个整数,按先大后小的顺序输出a和b
- 小明陪你编游戏系列(一)win32游戏开发快速入门
- 用window live writer无法离线编辑CSDN博客
- bf533 GPIO 学习
- 回顾
- Android中ListView下拉刷新的实现
- unity各平台路径,存放数据!
- IOS: UINavigationController 视图控制器