2.2.10—单链表—Copy List with Random Pointer

来源:互联网 发布:魔兽争霸3全屏软件 编辑:程序博客网 时间:2024/06/03 07:46
描述
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;elseq->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();}

原创粉丝点击