【问题标题】:link list insert() print();链接列表插入()打印();
【发布时间】:2015-04-12 03:23:21
【问题描述】:

我是初学者,我已经创建了链接列表,但我的代码无法正常工作。请提前帮助谢谢

#include <iostream>
using namespace ::std;

class node{
public:

    int data;
    node *link;
};


class linklist{
private:
    node *head=NULL;
    node *tail;
    node *temp;
public:
    // I think there is some issue but it seems perfect to me plz help 
    void insert(int n)
    {

        if(head==NULL)
        {
        tail=new node;
        tail->data=n;
        tail->link=NULL;
        head=tail;
        temp=tail;

        }
        else
        {
            tail=new node;
            tail->data=n;
            tail->link=NULL;
            temp->link=tail;


        }
    }
    void print()
    {
        while(head->link==NULL)
        {
            cout<<head->data<<endl;
            head=head->link;
        }

    }

};

int main() {
    linklist s;
    cout<<"how many numbers you want to enter"<<endl;
    int n,l;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cout<<"enter nummber";

        cin>>l;
        s.insert(l);
        s.print();
    }

   }

打印部分后打印不做,继续打印当前元素

【问题讨论】:

    标签: c++ list printing insert


    【解决方案1】:

    您的代码中有一些错误。

    1. print函数每次都会改变head的值,你需要使用局部变量。此外,while 循环的条件是错误的。

      void print()
      {
         node* t = head;
         while(t->link!=NULL)
         {
            cout<<t->data<<endl;
            t=t->link;
         }
      }
      
    2. 添加新节点时不要更改temp

      else
      {
          tail=new node;
          tail->data=n;
          tail->link=NULL;
          temp->link=tail;
          temp = tail; // here
      }
      

    【讨论】:

      猜你喜欢
      • 2017-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多