我最近一直在尝试学习 C/C++。我已经编写了一个简单的链表程序,它应该可以工作并且它实际上可以工作,但只有当链表的标题(node* mother
)是一个全局变量并且不用作函数(void new_node(int number)
)的参数时 - 这个函数是一个构造函数(我我使用 C 语法)。
下面的这个程序工作正常,但我不能创建多个链表:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
struct node {
node * next;
int number;
};
node * mother = NULL;
void new_node(int number)
{
node * newNode = (node*) malloc(sizeof(node));
newNode -> next = NULL;
newNode -> number = number;
if (mother == NULL){
mother = newNode;
}
else{
node* temp = mother;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = newNode;
}
}
void destroy(){
node* ntemp = mother;
mother = NULL;
node* t;
while(ntemp != NULL){
t = ntemp->next;
free(ntemp);
ntemp = t;
}
}
void printAll(){
node *tmp;
tmp = mother;
while (tmp != NULL){
cout <<"value is : " << tmp->number <<endl;
tmp = tmp->next;
}
}
int main()
{
cout <<"size is " << sizeof(node*) <<endl;
new_node(5);
new_node(17);
new_node(-54);
new_node(3);
new_node(4);
new_node(-24);
new_node(10);
printAll();
return 0;
}
但是,如果我将node* mother
其用作 function 的参数new_node
,则它不起作用-它仅打印节点的大小:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
struct node {
node * next;
int number;
};
void new_node(node* mother, int number){
node * newNode = (node*) malloc(sizeof(node));
newNode -> next = NULL;
newNode -> number = number;
if (mother == NULL){
mother = newNode;
}
else{
node* temp = mother;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = newNode;
}
}
void destroy(node * mother){
node* ntemp = mother;
mother = NULL;
node* t;
while(ntemp != NULL){
t = ntemp->next;
free(ntemp);
ntemp = t;
}
}
void printAll(node * mother){
node *tmp;
tmp = mother;
while (tmp != NULL){
cout <<"value is : " << tmp->number <<endl;
tmp = tmp->next;
}
}
int main()
{
node * mother = NULL;
cout <<"size is " << sizeof(node*) <<endl;
new_node(mother, 5);
new_node(mother, 17);
new_node(mother, -54);
new_node(mother, 3);
new_node(mother, 4);
new_node(mother, -24);
new_node(mother, 10);
printAll(mother);
return 0;
}
第一个程序的输出:
size is 8
value is : 5
value is : 17
value is : -54
value is : 3
value is : 4
value is : -24
value is : 10
第二个程序的输出:
size is 8
问题是,为什么这个程序的行为如此不同?