无法打印链表的第一个元素 我创建了这个C++程序来创建链表,但是我不能打印列表的第一个元素。 请帮忙

无法打印链表的第一个元素 我创建了这个C++程序来创建链表,但是我不能打印列表的第一个元素。 请帮忙,c++,linked-list,C++,Linked List,这是我的密码 #include <iostream> #include <cstdlib> #include <cstdio> using namespace std; class Node{ public: int data; Node* next; void Insert(int x); void Print(); }; Node* head; void Node::Insert(int x){ Node

这是我的密码

#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;

class Node{
    public:
    int data;
    Node* next;
    void Insert(int x);
    void Print();
};
Node* head;

void Node::Insert(int x){
    Node* temp=new Node();
    temp->data=x;
    temp->next=head;
    head=temp;
}

void Node::Print(){
    Node* temp=head;
    cout<<"List is "<<endl;
    while(temp->next!=NULL){
        cout<<temp->data<<"  ";
        temp=temp->next;
    }
    cout<<endl;
}

int main(){
    head=NULL;
    Node q;
    cout<<"Enter number of elements"<<endl;
    int n;
    cin>>n;
    int x;
    for(int i=0; i<n; i++){
        cout<<"ENter numbeR"<<endl;
        cin>>x;
        q.Insert(x);
        q.Print();
    }
    return 0;
}
#包括
#包括
#包括
使用名称空间std;
类节点{
公众:
int数据;
节点*下一步;
无效插入(int x);
作废打印();
};
节点*头;
void节点::插入(int x){
Node*temp=新节点();
温度->数据=x;
温度->下一步=头部;
压头=温度;
}
void节点::Print(){
节点*温度=头部;

cout在打印功能中,将
temp->next
更改为
temp

以下是我在输出演示格式中进行了少量修改的更新代码:

#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;

class Node{
public:
    int data;
    Node* next;
    void Insert(int x);
    void Print();
};
Node* head;

void Node::Insert(int x){
    Node* temp=new Node();
    temp->data=x;
    temp->next=head;
    head=temp;
}

void Node::Print(){
    Node* temp=head;
    cout<<"List is "<<endl;
    while(temp!=NULL){
        cout<<temp->data<<"  ";
        temp=temp->next;
    }
    cout<<endl;
}

int main(){
    head=NULL;
    Node q;
    cout<<"Enter number of elements: ";
    int n;
    cin>>n;
    int x;
    for(int i=0; i<n; i++){
        cout<<"Input node element: ";
        cin>>x;
        q.Insert(x);
        q.Print();
    }
    return 0;
}
#包括
#包括
#包括
使用名称空间std;
类节点{
公众:
int数据;
节点*下一步;
无效插入(int x);
作废打印();
};
节点*头;
void节点::插入(int x){
Node*temp=新节点();
温度->数据=x;
温度->下一步=头部;
压头=温度;
}
void节点::Print(){
节点*温度=头部;
cout错误在于:

while(temp->next!=NULL){
打印时。当列表只有一个元素时,该元素的
next
属性将为
NULL
。但是,由于此限制,程序不会进入while循环,因此不会打印它。您可以将其替换为:

while(temp!=NULL){

然后,将打印每个非空元素,即列表中的所有元素。

我可以建议稍微重新设计一下吗?您有一个列表,每个列表都有节点。因此,创建一个
list
类,其中包含
Node
对象的列表。
list
类具有添加节点的功能和打印节点的功能。
Node
类只有值和到列表中下一个节点的链接。希望能让事情变得简单一点,并且更有意义(在单个节点上调用
Print
函数来打印整个列表?)