[C++][資料結構][演算法]單鏈式結構的深拷貝

來源:互聯網
上載者:User

標籤:

單鏈式結構是相當普遍的一種結構。它不但被廣泛地用來實現單鏈表,棧,隊列等資料結構,而且還是譚浩強先生《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 something4 // 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 copy21   while (*dst) { // clear22     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   { // init38     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   // destory54   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 }

 

[C++][資料結構][演算法]單鏈式結構的深拷貝

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.