打印链表-C++
我有一个基本问题。int存储[]={8,6,4,2}。为什么打印的是2 4 6 8而不是8 6 4 2?你能解释一下原因吗?代码的哪一部分导致了它?我不明白 代码如下:打印链表-C++,c++,linked-list,C++,Linked List,我有一个基本问题。int存储[]={8,6,4,2}。为什么打印的是2 4 6 8而不是8 6 4 2?你能解释一下原因吗?代码的哪一部分导致了它?我不明白 代码如下: #include <iostream> #include <string> #include <cstdlib> #include <ctime> using namespace std; struct node { int info; n
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
struct node {
int info;
node *next;
node::node ()
{}
node::node (const int & s, node * link)
: info(s), next (link)
{}
};
void DisplayList (node * head)
{
cout << "The list content is: ";
node * ptr = head;
while (ptr != NULL)
{
cout << ptr ->info << " ";
ptr = ptr->next;
}
cout << endl<<endl;
}
int main()
{
int storage[] = {8,6,4,2};
node *head = NULL;
node *temp = NULL;
for (int k=0; k < 4; k++) {
temp = new node();
temp->info = storage[k];
temp->next = head;
head = temp;
}
DisplayList (head);
cin.ignore();
cin.get();
return 0;
}此代码:
int storage[] = {8,6,4,2};
node *head = NULL;
node *temp = NULL;
for (int k=0; k < 4; k++) {
temp = new node();
temp->info = storage[k];
temp->next = head; // <----- here, temp is before head
head = temp; // head is made first node again
}
按照{8,6,4,2}中的顺序,在head之前为每个元素添加前缀。因此,您以相反的顺序创建列表。您的头被您创建的每个新节点覆盖,因此for循环以相反的顺序追加
这就是你想要的
for (int k=0; k < 4; k++)
{
temp = new node();
temp->info = storage[k];
temp->next=NULL;
if(head==NULL)
head=temp;
else
head->next=temp;
}
您可以从存储的另一端开始填充,也可以执行以下操作:
int storage[] = {8,6,4,2};
node *head = NULL;
node *temp = NULL;
node *previous = NULL;
for (int k=0; k < 4; k++) {
temp = new node();
if (head == NULL)
{
head = temp;
}
if (previous != NULL)
{
previous->next = temp;
}
temp->info = storage[k];
previous = temp;
}
为什么不在调试器中单步执行代码呢?这样你会学到更多…我甚至不知道如何调试。我只是个初学者。