席八,迭代创建链表就是个坑货
生活随笔
收集整理的這篇文章主要介紹了
席八,迭代创建链表就是个坑货
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
大家先來看看這樣一段代碼,看能否自己得出輸出結果。
#include <iostream> using namespace std; struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {} }; int a[10000]; int n; void creatLinkedList(ListNode *&cur, int i) {if (i == n)return ;cur = new ListNode(a[i]);creatLinkedList(cur->next, i+1); } int main() {while (cin >> n){ListNode *head1 = NULL;ListNode *head2 = NULL;ListNode *cur = head1;for (int i = 0; i < n; i ++){cin>>a[i];if (i)cur = new ListNode(a[i]);else {head1 = new ListNode(a[0]);cur = head1; }cur = cur -> next;}cur = head2;creatLinkedList(head2, 0);cur = head1;cout<<"created by iteration:";while (cur != NULL){cout << cur->val<<' ';cur = cur->next; }cout <<endl;cur = head2;cout<<"created by recursion:";while (cur != NULL){cout << cur->val<<' ';cur = cur->next; }cout <<endl;} } 是不是結果應該是一模一樣的,那說明你還沒有深入理解代碼背后的一些操作,不賣關子了,其計算結果應該是這樣的:
原因就在于,當使用上述方式的迭代建立鏈表時,cur每次都會指向NULL,而NULL的存儲位置是內存中固定的一個地址,這樣當cur=cur->next的時候,就等于cur=NULL,因此cur和其前驅的關系實際上已經斷開了,因此原想做成的鏈已經被拆成一個個單一的節點,而使用遞歸時,程序控制參數從右向左一一入棧,產生一個參數的副本,當傳遞cur->next的時候相當于有一個cur->next = new ListNode的過程,因此連接得以保留。
因此如果要使用迭代創建鏈表的話,應當這么寫,即先保護好聯系再跳轉:
總結
以上是生活随笔為你收集整理的席八,迭代创建链表就是个坑货的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: U821升级到U810.1注意事项
- 下一篇: PV VG LV命令简版