user1561358
user1561358

Reputation: 304

Linked list - not linking

This seems pretty straightforward. Create a linked list, populate it with some structs and than print them out. However for some reason only first entry stored in head variable is created and nothing else. The program get caught in a loop in the addHorse() method. Specifically the else part. I looks like first entry has itself stored in the *next variable but I specifically changed it to NULL when I created it.

Any idea what I did wrong<

#include <stdio.h>
#include <stdlib.h>
#include <string.h>



typedef struct horse{
char name[12];
char color[10];
int price;
struct horse *next;
}HORSE;

HORSE *head  = NULL;

void addHorse(HORSE * newHorse) {
    HORSE *lastHorse;
    if(head == NULL){
        head = newHorse;
        head->next = NULL;
    }
    else{
        lastHorse = head;
        while(lastHorse->next != NULL){
            lastHorse = lastHorse->next;
        }
    lastHorse->next = newHorse;
    }

    newHorse->next = NULL;
}

HORSE *create(){
    HORSE *hr;
    hr=(HORSE *) malloc (sizeof (HORSE));
    if (hr==NULL){
        printf("spatne");
        exit (-1);
    }
    hr->next=NULL;

    return hr;
}

void makeHorses(){
    int i, p, k;
    HORSE *newHorse;
    p = 40;
    k = 10;
    newHorse = create();
    for(i = 0;i <= p;i++){
        if((i%3) == 0){
            strcpy(newHorse->name,"semik");
            if(i<=k){
                newHorse->price = 20000;
            }
            else{
                newHorse->price = 6000;
            }
        }
        else{
            strcpy(newHorse->name,"hryzal");
            if(i<=k){
                newHorse->price = 20000;
            }
            else{
                newHorse->price = 6000;
            }
        }
        strcpy(newHorse->color, "black");
        newHorse->next = NULL;
        addHorse(newHorse);
    }
}

void printHorses(){
    HORSE *firstHorse;
    firstHorse = head;
    while((firstHorse->next) != NULL){
        printf("%s\n", firstHorse->name);
        printf("%s\n", firstHorse->color);
        printf("%d\n", firstHorse->price);
        firstHorse = firstHorse->next;
    }
}

int main(){   
    makeHorses();
    printHorses();
    return 0;
}

Upvotes: 1

Views: 179

Answers (1)

Rohan
Rohan

Reputation: 53316

You should do newHorse = create(); in each iteration of for loop in makeHorses() function.

With your code, you are adding same node multiple times.

Upvotes: 3

Related Questions