描述
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指针。
- 第三步,再次遍历链表,把原链表的节点和复制出来的节点拆成两个链表。
代码
Python
1 | # Definition for singly-linked list with a random pointer. |