-3

我有一个基本问题。整数存储[] = {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;
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;

}

4

3 回答 3

2

这段代码:

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
}

在 .之前 添加每个元素head,因为它是按顺序处理的,在{8,6,4,2}. 因此,您以相反的顺序创建列表。

于 2013-03-03T13:52:27.697 回答
0

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; 
}
于 2013-03-03T13:57:52.503 回答
0

要么从存储的另一端开始填充,要么可以这样做:

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;
}
于 2013-03-03T13:57:53.110 回答