William Le
William Le

Reputation: 1171

My linked list does not print out as expected?

I'm trying so hard to find out what's gone wrong with the result. it only prints out 1 information instead of everything in the list. I checked every single function from insert to display but nothing is different from the sample that works. I'm really at a loss now. At first, I thought it was the *l that I forgot to malloc, the isEmptyTrain function was wrong... but after fixing all of these it still does not work at all. Can you help me with this exercise? Below is my code:

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

Thank you!

Upvotes: 0

Views: 45

Answers (1)

Igor Tandetnik
Igor Tandetnik

Reputation: 52471

length(l) returns a bool. You then use it as an integer, whereby it's converted to either 0 or 1; it can't ever return a value greater than 1.

Upvotes: 1

Related Questions