2013-03-03 199 views
-3

我有一个基本问题。 int storage [] = {8,6,4,2}。为什么打印2 4 6 8而不是8 6 4 2?你能解释为什么吗?哪部分代码会导致它?我无法理解。打印链接列表 - C++

下面是代码:

#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; 

}

+0

调试它,看看! – StoryTeller 2013-03-03 13:52:35

+0

为什么不在调试器中单步执行代码?你会学到更多的方法...... – 2013-03-03 13:53:02

+0

我甚至不知道如何调试。我只是一个初学者编码器。 – Nordin 2013-03-03 14:30:51

回答

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}。因此,您可以按相反的顺序创建列表。

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; 
} 
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; 
}