2.2.10—单链表—Copy List with Random Pointer

描述
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.

#include<iostream>
using namespace std;

struct node
{
	int data;
	node *next;
	node *additional;
};
class mylist
{
	node *head;
public:
	mylist()
	{
		head = new node();
		head->next = NULL;
		head->additional = NULL;
	}
	void CreateList(int a[], int n);
	void Display();
	friend void CopyList(mylist &list, mylist &copy_list);
	~mylist();
};
void mylist::CreateList(int a[], int n)
{
	node *p = head;
	for (int i = 0; i < n; i++)
	{
		node *q = new node();
		q->data = a[i];
		q->additional = NULL;
		p->next = q;
		p = q;
	}
	p->next = NULL;
	//===增加额外指针,程序中只做两个节点
	node *q = head->next;
	q->additional = q->next->next;
	q = head->next->next;
	q->additional = q->next->next;
}
void mylist::Display()
{
	node *p = head->next;
	while (p)
	{
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
	//===
	p = head->next;
	while (p)
	{
		if (p->additional)
			cout << "结点" << p->data << "的附加指针指向结点" << p->additional->data << endl;
		p = p->next;
	}
}
void CopyList(mylist &list, mylist &copy_list)
{
	node *p = list.head->next;
	while (p)
	{
		node *q = new node();
		q->data = p->data;
		q->additional = NULL;

		if (p->next != NULL)
		{
			q->next = p->next;
			p->next = q;
			p = q->next;
		}
		else
		{
			q->next = NULL;
			p->next = q;
			p = q->next;
		}
	}
	//===
	p = list.head->next;
	node *q = p->next;
	copy_list.head->next=q;
	while (p)
	{
		if (q->next != NULL)
		{
			p->next = p->next->next;
			q->next = q->next->next;
			if (p->additional)
				q->additional = p->additional->next;
			else
				q->additional = NULL;
			p = p->next;
			q = q->next;
		}
		else
		{
			p->next = NULL;
			break;
		}
	}
}

mylist::~mylist()
{
	node *p = head;
	while (p)
	{
		node *temp = p->next;
		delete p;
		p = temp;
	}
}
int main()
{
	//===
	const int n = 4;
	int a[n] = { 1, 2, 3, 4};
	mylist list;
	list.CreateList(a, n);
	list.Display();
	cout << endl;
	//===
	mylist copy_list;
	CopyList(list, copy_list);
	copy_list.Display();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值