您的位置:首页 > 运维架构

2.2.10—单链表—Copy List with Random Pointer

2017-08-04 11:00 295 查看
描述

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 ©_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 ©_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
= { 1, 2, 3, 4};
mylist list;
list.CreateList(a, n);
list.Display();
cout << endl;
//===
mylist copy_list;
CopyList(list, copy_list);
copy_list.Display();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: