美文网首页算法集锦(C++)
深度复制一个链表

深度复制一个链表

作者: KrisBento | 来源:发表于2016-05-20 12:46 被阅读0次

题目描述

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.

解题思路

  • 先对原链表中的每个结点复制一个新的结点,并将复制的新结点的next和random域都和原结点的指向一样;
  • 再将原链表中的结点的next域都指向相应的新复制的结点;
  • 然后调整复制的结点的random域的指向,指向相应的copy结点;
  • 最后恢复原链表的连接情况,主要是next域的指向,由指向copy结点转成指向原链表中相应的结点。

主要实现代码

class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        if(!head){
            return NULL;
        }
        RandomListNode *currNode=head;
        while(currNode){
            RandomListNode *copyNode=new RandomListNode(currNode->label);
            copyNode->next=currNode->next;
            copyNode->random=currNode->random;
            currNode->next=copyNode;
            currNode=copyNode->next;
        }
        currNode=head;
        while(currNode){//找到copy的结点的实际random结点
            if(currNode->next->random){
                currNode->next->random=currNode->random->next;
            }
            currNode=currNode->next->next;
        }
        RandomListNode *copyList=new RandomListNode(0);
        copyList->next=head;
        RandomListNode *pHead=copyList;
        currNode=head;
        while(currNode){
            pHead->next=currNode->next;
            pHead=currNode->next;
            currNode->next=pHead->next;
            currNode=pHead->next;
        }
        return copyList->next;
    }
};

相关文章

网友评论

    本文标题:深度复制一个链表

    本文链接:https://www.haomeiwen.com/subject/rylnrttx.html