我的链表没有按预期打印出来?

  • 本文关键字:打印 链表 c++ linked-list
  • 更新时间 :
  • 英文 :


我非常努力地找出结果出了什么问题。 它只打印出 1 条信息,而不是列表中的所有信息。我检查了从插入到显示的每个功能,但与工作的示例没有什么不同。我现在真的很茫然。起初,我以为是我忘记了malloc的*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;}

谢谢!

length(l)返回一个bool。然后,将其用作整数,从而将其转换为 0 或 1;它永远不能返回大于 1 的值。

相关内容

  • 没有找到相关文章

最新更新