link 列表插入()打印();

link list insert() print();

我是初学者,我创建了 link 列表,但我的代码无法正常工作。请提前帮助thx

#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();
    }

   }

打印部分打印后没有进行,它继续打印当前元素

你的代码有一些错误。

  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
    }