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

// 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;
}
posted @ 2016-11-03 17:13  wdan2016  阅读(1010)  评论(0编辑  收藏  举报