C++ 链表不适用于输入

C++ 链表不适用于输入,c++,C++,我正在编写一段代码,它接受用户输入的整数,创建一个链表,然后打印出链表。但是,当我输入值1,2,3,4,5时,输出仅为5 请告诉我哪里错了 代码如下: include"iostream" using namespace std; struct node { int number; node* next; }; int main() { node* head; head = NULL; int i,n,x; cin>>n; c

我正在编写一段代码,它接受用户输入的整数,创建一个链表,然后打印出链表。但是,当我输入值1,2,3,4,5时,输出仅为5

请告诉我哪里错了

代码如下:

include"iostream"
using namespace std;

struct node
{
    int number;
    node* next;
};

int main()
{
    node* head;
    head = NULL;
    int i,n,x;
    cin>>n;
    cout<<endl;
    for(i=0;i<n;i++)
    {
        cin>>x;
        //Insert(x);
        node* temp;
        temp = new node;
        temp->number = x;
        temp->next = NULL;
        head = temp;
    }
    //Print();
    node* temp;
    temp = head;
    while(temp != NULL)
    {
        for(int j=0; j<n; j++)
            cout<<temp->number<<" ";
            temp = temp->next;
    }
}
这看起来有点错误:

看看是否效果更好

此外:

正如@crashmstr指出的,您的插入逻辑是错误的:

for(i=0;i<n;i++)
{
    cin>>x;
    //Insert(x);
    node* temp;
    temp = new node;
    temp->number = x;
    temp->next = NULL; // this should point to the nextnode
    head = temp;
}
请使用:

#include <iostream> // correct!

请记住,在设置head指针时,仅当列表为空时,即head==NULL时,才应这样做。我们应该在创建新节点后执行此操作,以便知道要设置的头:

还有一个问题。temp应该在每次创建时添加到列表的末尾。如果列表为空,那么head是列表的结尾,但是如果列表已经有元素,那么我们需要转到末尾,并将该节点的下一个指针设置为temp。这相当简单,只需要一个while循环就可以在列表上迭代到最后:

if (head == NULL)
    head = temp;
else // the list is not empty
{
    // so we need to go to the end
    node* p = head;
    while (p->next != NULL)
        p = p->next; // keep going through

    // p now points to the last node
    p->next = temp;
}
还可以选择保留指向插入的最后一个元素的prev节点。这样,我们就不必每次都通过列表来找到结尾:

node* head = NULL, prev = NULL;

for (/* ... */)
{
    // ...
    if (head == NULL)
        head = prev = temp;
    else
    {
        prev->next = temp;
        prev = temp;
    }
}
最后一件事是你打印的方式。此处不应该有嵌套的for循环:

while (temp != NULL)
{
    for(int j = 0; j < n; j++)
        cout << temp->number << " ";
        temp = temp->next;
}

取出将使其正确打印。

您的插入逻辑错误。您可以更改head指向的对象,但不链接旧的head。您还使用了非常类似C的语法,并且没有利用C++的类。这样只会输出一个5,因为插入逻辑是错误的,但肯定是对输出代码的更正。更改head会使它指向列表中的最后一个节点。打印出来会得到54321@0x499602D2。我尽量保持简单,不觉得有必要为他做所有的工作,只是指出一些错误。
#include <iostream> // correct!
node* temp = new node;
temp->number = x;
temp->next = NULL;

if (head == NULL) // if the list is empty then...
    head = temp;  // temp is the start of the list
if (head == NULL)
    head = temp;
else // the list is not empty
{
    // so we need to go to the end
    node* p = head;
    while (p->next != NULL)
        p = p->next; // keep going through

    // p now points to the last node
    p->next = temp;
}
node* head = NULL, prev = NULL;

for (/* ... */)
{
    // ...
    if (head == NULL)
        head = prev = temp;
    else
    {
        prev->next = temp;
        prev = temp;
    }
}
while (temp != NULL)
{
    for(int j = 0; j < n; j++)
        cout << temp->number << " ";
        temp = temp->next;
}