题目描述
blablabla
样例
/**
* Definition for singly-linked list with a random pointer.
* struct ListNode {
* int val;
* ListNode *next, *random;
* ListNode(int x) : val(x), next(NULL), random(NULL) {}
* };
*/
class Solution {
public:
ListNode *copyRandomList(ListNode *head) {
if (!head) return head;
auto p = head;
while(p) {
auto tmp = new ListNode(p->val);
auto t = p->next;
p->next = tmp;
tmp->next = t;
p = t;
}
p = head;
while(p){
if(p->random)
p->next->random = p->random->next;
p = p->next->next;
}
p = head;
auto dummy = new ListNode(-1);
auto cur = dummy;
while(p) {
cur->next = p->next;
cur = cur->next;
p = cur->next;
}
return dummy->next;
}
};
auto dummy=new ListNode(-1);
auto cur=dummy;
auto q=head;//恢复原链表
for(auto p=head;p;p=p->next){
cur->next=p->next;
现在题目要求不能修改原链表了啊
对,最后一步要把原链表的指针复原
画图挺好理解的,这要是考试,我觉的我可能想不到