Copy List with Random Pointer
来源:互联网 发布:特朗普 金正恩 知乎 编辑:程序博客网 时间:2024/06/11 23:01
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.
深拷贝链表。
Step 1: 首先指向在原链表的每个节点后面,复制一个新的节点,原链表长度变为 2 倍,
random 指针指向的是 原链表节点 random 指针指向的节点的后面的那个节点
Step 2: 将链表拆成两个 lists
RandomListNode *copyRandomList(RandomListNode *head){ if (head == NULL) return NULL; RandomListNode *pos1 = head, *pos2 = head->next; while (pos1 != NULL)//add new list2 into { pos1->next = new RandomListNode(pos1->label); pos1->next->next = pos2; pos1 = pos2; if (pos2 != NULL) pos2 = pos2->next; } pos1 = head; pos2 = head->next; while (pos1 != NULL)//build random pointer for list2 { if (pos1->random == NULL) pos2->random = NULL; else pos2->random = pos1->random->next; pos1 = pos1->next->next; if (pos2->next != NULL) pos2 = pos2->next->next; } RandomListNode *res = head->next; pos1 = head, pos2=head->next; while(pos2->next != NULL)//apart list1 and list2 { pos1->next = pos2->next; pos1 = pos2; pos2 = pos2->next; } pos1->next = NULL; return res;}
0 0
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- 算法之动态规划(LCS最长公共子序列, edit distance,交叉子串)
- VC++深入详解(孙鑫)在VS2010学习中碰到的几个调试问题
- 解决办法:Access restriction: The type JPEGImageEncoder is not accessible due to restriction
- java中枚举举例说明
- error C2440: 'static_cast' : cannot convert from 'void (__thiscall CChatDlg::* )(WPARAM,LPARAM)' to
- Copy List with Random Pointer
- 将prezi试用期无限延长的办法
- lldb stack base pointer
- Asteroids
- C# Winform App.config加密 aspnet_regiis
- Intent.ACTION_VIEW
- gcc命令objdump用法
- GDB TO LLDB COMMAND MAP
- Ubuntu 14.04下oracle sqldeveloper只能用管理员运行的解决办法