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.
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(); }
相关文章推荐
- 2.2.10CopyListwithRandomPointer
- 2.2.10 Copy List with Random Pointer
- Copy List with Random Pointer
- leetcode第13题(copy-list-with-random-pointer)
- 【LeetCode】Copy List with Random Pointer
- LeetCode Copy List with Random Pointer
- copy-list-with-random-pointer
- Copy List with Random Pointer
- [LeetCode] 132: Copy List with Random Pointer
- leetcode-Copy List with Random Pointer
- LeetCode - Copy List with Random Pointer
- leetcode 149: Copy List with Random Pointer
- LeetCode——Copy List with Random Pointer
- 第23题 Copy List with Random Pointer
- Copy List with Random Pointer
- Copy List with Random Pointer
- LeetCode138 Copy List with Random Pointer(深度复制带有随机指针的链表) Java题解
- Leetcode: Copy List with Random Pointer
- [LeetCode] - Copy List with Random Pointer
- 【LeetCode】Copy List with Random Pointer