输出为什么会溢出
<div class="blockcode"><blockquote>#include <iostream>
using namespace std;
struct node
{
int num;
struct node *next;
};
node* createList();
void traverseList(node*);
int main()
{
node *p = createList();
traverseList(p);
system("pause");
return 0;
}
node* createList()
{
node *head = new node;
head->next = NULL;
node *ptr = head;
int a;
cin >> a;
while (0 != a)
{
node *s = new node;
s->next = NULL;
s->num = a;
s->next = ptr->next;
ptr->next = s;
cin >> a;
}
return head;
}
void traverseList(node *l)
{
node* ptr = l;
while (NULL != ptr)
{
cout << ptr->num << endl;
ptr = ptr->next;
}
}</blockquote></div><br /> 之所以输出这个感觉莫名其妙的数字,是因为在
node* createList();
这个函数体里:
node *head = new node;
初始化时已经new出对象,因为有了对象,所以这时head这个对象里的对应的结构
struct node
{
int num;
struct node *next;
};
中的成员变量
int num;
这里的对象head里的成员num已经有了一个值。 修改后代码:
#include <iostream>
using namespace std;
struct node
{
int num;
struct node *next;
};
node* createList();
void traverseList(node*);
int main()
{
node *p = createList();
traverseList(p);
system("pause");
return 0;
}
node* createList()
{
node *head = new node;
head->next = NULL;
head->num = NULL;
node *ptr = head;
int a;
cin >> a;
while (0 != a)
{
node *s = new node;
s->next = NULL;
s->num = a;
s->next = ptr->next;
ptr->next = s;
cin >> a;
}
return head;
}
void traverseList(node *l)
{
node* ptr = l;
while (NULL != ptr)
{
cout << ptr->num << endl;
ptr = ptr->next;
}
}
页:
[1]