使用递归与迭代在插入链表末尾插入

时间:2016-10-17 19:46:20

标签: c++ recursion linked-list

使用递归在链表末尾插入的函数看起来像这样

     // Main..
     for(int i=0;i<n;i++){
       cin>>x;
       insert(head,x);
     }

     void insert(struct node*&h,int x){
      if(h==NULL){
       h=new node(x);
       return;
      }
      insert(h->next,x);
     }

但是,如果我在迭代中做同样的事情,那么它的工作方式不同,只有一个节点。

     void insert(struct node* &h,int x){
             if(h==NULL){
             h=new node(x);
             return;
            }
        struct node* go=h;
        while(go){     //At (go==NULL) it should point to next of last node
         go=go->next;   // I know it should be go->next!=NULL condition.
       }
         go=new node(x);//Assigning next of last to new node.
   }

我有严重的精神障碍。任何人都可以帮助为什么它不起作用?我该怎么做才能让它发挥作用?

1 个答案:

答案 0 :(得分:1)

这里的问题是你循环直到echo '<tr align="right" class="loc"><td class="plus_minus" width="20" align="center" bordercolor="#000000" style="cursor:pointer;font-size:10pt;font-weight:bold; border-style:solid;border-width:1pt">+</td>'; 不为空。好的,一旦修复,你循环直到go为空,

然后你只需用go覆盖一个空指针。但这并没有将它与您现有的列表联系起来。

改为:

new

在第一次迭代时,void insert(struct node* &h,int x) { if(h==NULL) { h=new node(x); return; } struct node* go=h; // move until last element while(go->next) { go=go->next; } // create a node at the end go->next=new node(x);//Assigning next of last to new node. } 保证为非空(由第一go条件检查)。 只需检查第一个if元素是否为空,然后在此处插入新节点。

相关问题