打印链表 - C ++

时间:2013-03-03 13:49:57

标签: c++ linked-list

我有一个基本问题。 int storage [] = {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;

}

3 个答案:

答案 0 :(得分: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}之前的每个元素。因此,您以相反的顺序创建列表。

答案 1 :(得分: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; 
}

答案 2 :(得分: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;
}