复杂链表的深度拷贝(给定一个链表,每个节点包涵一个额外增加的随机指针,返回这个链表的深度拷贝)

RNode.h

#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

typedef struct RNode {
    int v;
    RNode* ramdom;
    RNode * next;
}RNode;

RNode.c

#include"RNode"

RNode *Copy(RNode *head){
    if (head = NULL){
        return NULL;
    }
    //分三步走
    RNode* oldNode = head;
//第一步,只复制节点中value和next,让新节点跟在老节点后边
    while (oldNode != NULL){
        RNode* newNode = (RNode*)malloc(sizeof(RNode));
        newNode->v = oldNode->v;

        RNode* oldNext = oldNode->next;
        newNode->next = oldNext;
        oldNode->next= newNode;
        oldNode = oldNext;
    }
//第二步,再处理ramdom的复制
    oldNode = head;
    while (oldNode != NULL){
        RNode * newNode = oldNode->next;
        if (oldNode->ramdom == NULL){
            newNode->ramdom = NULL;
        }
        else{
            newNode->ramdom = oldNode->ramdom->next;
        }
        oldNode = newNode->next;
    }
   //第三步,把链表拆成两个
    oldNode = head;
    RNode *newHead = head->next;//把新节点的第一个节点保存一下
    while (oldNode != NULL){
        RNode * newNode = oldNode->next;
        oldNode->next = newNode->next;
        if (newNode->next != NULL){
            newNode->next = newNode->next->next;
        }
        oldNode = oldNode->next;
    }
    return newHead;
}
RNode *BuyNode(int v){
    RNode *node = (RNode*)malloc(sizeof(RNode));
    node->v = v;
    node->next = NULL;
    node->ramdom = NULL;
    return node;
}

main.c

#include"RNode"
int main(){
    RNode *n1 = BuyNode(1);
    RNode *n2 = BuyNode(2);
    RNode *n3 = BuyNode(3);
    RNode *n4 = BuyNode(4);
    n1->next = n2;
    n2->next = n3;
    n3->next = n4;
    n1->ramdom = n3;
    n2->ramdom = n1;
    n3->ramdom = n3;
    n4->ramdom = NULL;
    RNode *rn1 = Copy(n1);
    RNode *rn2 = rn1->next;
    RNode *rn3 = rn2->next;
    RNode *rn4 = rn3->next;
    assert(rn1->v == n1->v);
    assert(rn2->v == n2->v);
    assert(rn3->v == n3->v);
    assert(rn4->v == n4->v);
    assert(rn1->ramdom == rn3);
    assert(rn2->ramdom == rn1);
    assert(rn3->ramdom == rn3);
    assert(rn4->ramdom == NULL);
}

猜你喜欢

转载自blog.csdn.net/qq_41832361/article/details/89682745
今日推荐