输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序...

本文介绍了一种通过两次遍历实现复杂链表复制的方法。首先顺序遍历创建新链表,然后再次遍历设置random指针,实现了链表的完全复制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// test20.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<cstring>
#include<string.h>
#include<deque>

using namespace std;


struct RandomListNode {
    int label;
    struct RandomListNode *next, *random;
    RandomListNode(int x) :
    label(x), next(NULL), random(NULL) {
    }
};

class Solution {
public:
    RandomListNode* Clone(RandomListNode* pHead)
    {
        //两次遍历pHead
        //第一次顺序遍历new出新的链表
        //第二次遍历random节点
        RandomListNode *p = pHead;
        RandomListNode *newHead = NULL;
        RandomListNode *pre = NULL;
        //第一次遍历
        if (p != NULL)
        {
            newHead = new RandomListNode(p->label);
            if (p->random != NULL)
                newHead->random = new RandomListNode(p->random->label);
            pre = newHead;
            p = p->next;
        }
        
        while (p!=NULL)
        {
            pre->next = new RandomListNode(p->label);
            pre = pre->next;
            if (p->random != NULL)
                pre->random = new RandomListNode(p->random->label);
            p = p->next;
        }

        //cout << "复制后的链表是:" << endl;
        //while (newHead != NULL)
        //{
        //  cout << newHead->label << "  ";
        //      newHead = newHead->next;
        //}
        //第二次遍历
    /*  cout << "复制后的链表是:" << endl;
        while (newHead != NULL)
        {
            cout << newHead->label << "  ";
            newHead = newHead->random;
        }*/
    
        return newHead;
    }
};

int main()
{
    
    Solution so;

    RandomListNode *node01 = new RandomListNode(1);
    RandomListNode *node02 = new RandomListNode(2);
    RandomListNode *node03 = new RandomListNode(3);
    RandomListNode *node04 = new RandomListNode(4);
    RandomListNode *node05 = new RandomListNode(5);
    RandomListNode *node06 = new RandomListNode(6);
    RandomListNode *node07 = new RandomListNode(7);
    RandomListNode *node08 = new RandomListNode(8);
    node01->next = node02;
    node02->next = node03;
    node03->next = node04;
    node04->next = node05;

    node01->random = node06;
    node06->random = node07;
    node07->random = node08;
    RandomListNode* T = so.Clone(node01);
    
    
    
    cout << endl;
    return 0;
}

转载于:https://www.cnblogs.com/wdan2016/p/6027386.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值