简体   繁体   English

链接列表 - 不链接

[英]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. 但是由于某种原因,只创建了存储在head变量中的第一个条目而没有其他条目。 The program get caught in a loop in the addHorse() method. 该程序陷入addHorse()方法的循环中。 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. 我看起来第一个条目本身存储在* next变量中,但我在创建它时专门将其更改为NULL。

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

You should do newHorse = create(); 你应该做newHorse = create(); in each iteration of for loop in makeHorses() function. makeHorses()函数的for循环的每次迭代中。

With your code, you are adding same node multiple times. 使用您的代码,您将多次添加相同的节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM