标签:
单链式结构是相当普遍的一种结构。它不但被广泛地用来实现单链表,栈,队列等数据结构,而且还是谭浩强先生《C程序设计》中唯一介绍到的数据结构——这充分体现了此数据结构结构的广泛性与实用性。
设我们的结构是这样的:
1 template <class value> 2 struct node { 3 value val; 4 node *next = nullptr; 5 };
然后定义并初始化了一个单链表list1:
1 typedef node<int> in; 2 in *list1 = new in; 3 // do something 4 // do something else
然后我们又定义了一个单链表list2:
1 in *list2;
现在我们想将list1深拷贝到list2,能不能写出一个通用函数呢?
我的实现:
1 template <class value> 2 void sldc(node<value> **dst, const node<value> *src) { // single list deep copy 3 while (*dst) { // clear 4 auto **tmp = &(*dst)->next; 5 delete tmp; 6 dst = tmp; 7 } 8 *dst = nullptr; 9 10 for (; src; src = src->next, dst = &(*dst)->next) { 11 *dst = new in; 12 (*dst)->val = src->val; 13 } 14 }
以下是一个demo:
1 #include <iostream> 2 3 template <class value> 4 struct node { 5 value val; 6 node<value> *next = nullptr; 7 8 void print() const { 9 for (const node<value> *p = this; p; p = p->next) { 10 std::cout << p->val << " "; 11 } 12 13 std::cout << std::endl; 14 } 15 }; 16 17 typedef node<int> in; 18 19 template <class value> 20 void sldc(node<value> **dst, const node<value> *src) { // single list deep copy 21 while (*dst) { // clear 22 auto **tmp = &(*dst)->next; 23 delete tmp; 24 dst = tmp; 25 } 26 *dst = nullptr; 27 28 for (; src; src = src->next, dst = &(*dst)->next) { 29 *dst = new in; 30 (*dst)->val = src->val; 31 } 32 } 33 34 int main() { 35 in *list1 = new in; 36 37 { // init 38 in **p = &list1; 39 for (int i = 0; i < 9; ++i, p = &(*p)->next) { 40 *p = new in; 41 (*p)->val = i; 42 } 43 } 44 45 // 46 47 list1->print(); 48 49 in *list2 = nullptr; 50 sldc(&list2, list1); 51 list2->print(); 52 53 // destory 54 in *p = list1; 55 56 while (p) { 57 auto *tmp = p->next; 58 delete p; 59 p = tmp; 60 } 61 62 p = list2; 63 64 while (p) { 65 auto *tmp = p->next; 66 delete p; 67 p = tmp; 68 } 69 }
标签:
原文地址:http://www.cnblogs.com/jt2001/p/sldc20150811.html