链表的复杂复制

要点:(1)复制next (2)复制random的(3)拆解

/**
 * 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 || head->next==NULL){
            return head;
        }
        RandomListNode *h=head;
        while(h){  //复制一个链表
            RandomListNode *p=h->next;
            RandomListNode *temp=new RandomListNode(h->label);
            temp->next=h->next;
            h->next=temp;
            h=p;
        }
        h=head;
        while(h!=NULL){  //复制random
            
            if(h->random!=NULL){
                h->next->random=h->random->next;
            }   
            h=h->next->next;
        }
        h=head;  //注意是一个一个的节点进行拆分
        RandomListNode *res=h->next;
        while(h->next){
            RandomListNode *temp=h->next;
            h->next=temp->next; //因为h->next->next 所以判断h->next
            h=temp;
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/u010325193/article/details/86322742
今日推荐