这看起来非常简单。创建一个链表,用一些结构填充它,然后打印出来。 但是由于某种原因,只创建了存储在head变量中的第一个条目而没有其他条目。该程序陷入addHorse()方法的循环中。特别是其他部分。我看起来第一个条目本身存储在* next变量中,但我在创建它时专门将其更改为NULL。
知道我做错了什么<
#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;
}
答案 0 :(得分:3)
您应该在newHorse = create();
函数的for循环的每次迭代中执行makeHorses()
。
使用您的代码,您将多次添加相同的节点。