我正在努力寻找结果出了什么问题。它只打印出1条信息,而不是列表中的所有信息。我检查了从插入到显示的每个函数,但是与工作的示例没有什么不同。我现在真的很茫然。起初,我以为是我忘记了* alloc的* l,isEmptyTrain函数是错误的……但是修复所有这些之后,它仍然根本无法工作。你可以帮我做这个练习吗?下面是我的代码:
typedef struct Car{
char name;
int number;
struct Car *pNext;
} Car;
typedef struct Train{
int size;
Car *pHead;
} Train;
Car *initCar(char name, int number){
// Car *car = (Car*)malloc(sizeof(*car));
Car *p = new(Car);
p->name = name;
p->number = number;
p->pNext = NULL;
return p;
}
//initList
void initTrain(Train *l){
l->size = 0;
l->pHead = NULL;
}
bool isTrainEmpty(Train *l){
return (l->size == 0);
}
bool isCarEmpty(Car *p){
return (p->number == 0);
}
bool length(Train *l){
return l->size;
}
void insert(Car *pNew, Train *l, Car *pOld = NULL){
//insert first
if(isTrainEmpty(l)){
l->pHead = pNew;
}
else{
pNew->pNext = pOld->pNext;
pOld->pNext = pNew;
}
l->size++;
}
void display(Train *l){
Car *p = l->pHead;
for(int i = 0; i < length(l); i++){
cout << "Car " << p->name << " has " << p->number << " passenger(s)" << endl;
p = p->pNext;
}
}
int main(){
Train *l, obj;
l = new(Train);
l = &obj;
char name;
int number = 0, size, add = 0, del = 0;
Car *p, *q = NULL;
initTrain(l);
cout << "Enter the length of the train: " << endl;
cin >> size;
if(size <= 0) {
cout << "The length must be greater than 0!" << endl;
return 0;
}
else
for(int i = 0; i < size; i++){
cout << "Enter the name of the car (1 char): " << endl;
cin >> name;
cout << "Enter the number of passengers on the car: " << endl;
cin >> number;
p = initCar(name, number);
if(i == 0){
insert(p, l);
}
else{
insert(p, l, q);
}
q = p;
}
display(l); return 0;}
谢谢!
答案 0 :(得分:1)
length(l)
返回一个bool
。然后将其用作整数,从而将其转换为0或1;它永远无法返回大于1的值。