题目的意思比较难理解,分为3步。第一步建立二重链表,第二步random指针的建立,第三步拆分二重链表。
/* // Definition for a Node. class Node { public: int val; Node* next; Node* random; Node(int _val) { val = _val; next = NULL; random = NULL; } }; */ class Solution { public: Node* copyRandomList(Node* head) { if(head==NULL) return {}; Node*st=head; while(st!=NULL)//生成二重链表 { Node*temp=new Node(st->val); temp->next=st->next; st->next=temp; st=st->next->next; } st=head; Node* pt,*temp; //处理random指针 while(st!=NULL) { pt=st->next; if(pt!=NULL&&st->random!=NULL) pt->random=st->random->next; st=st->next->next; } //重新穿针引线,处理链表顺序 Node *pre,*cur,*next,*res; pre=head; while(pre!=NULL) { if(pre==head) { res=pre->next; } cur=pre; if(pre->next!=NULL) pre=pre->next->next; next=cur->next; cur->next=pre; if(pre!=NULL) next->next=pre->next; } return res; } };
原文地址:https://www.cnblogs.com/legendcong/p/12512469.html
时间: 2024-10-31 07:49:46