2012-12-20 129 views
1

對此的輸出不正確。第二列火車的名字出現而不是第一列,而第一列火車的名字完全丟失。邏輯錯誤在哪裏?另外,根的目的是什麼?爲什麼我的鏈接列表不能按照正確的順序打印?

#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 
#include <string.h> 
struct trainset { 
    char name[50]; 
    int price; 
    struct trainset *next; 
}; 

void show_list(struct trainset *list); 

int main (void){ 

    struct trainset *root; 
    root = (struct trainset *)malloc(sizeof(struct trainset));  
    strncpy(root ->name, " ", 50); 
    root ->price = 0; 
    root ->next = 0; 

    struct trainset *first_train; 
    first_train = (struct trainset *) malloc(sizeof(struct trainset)); 
    root ->next = first_train; 
    strncpy(first_train->name, "Fantasy Train Set", 50); 
    first_train->price = 129; 
    first_train->next = NULL; 

    struct trainset *second_train; 
    second_train = (struct trainset *)malloc(sizeof(struct trainset)); 
    first_train->next = second_train; 
    strncpy(first_train->name, "Uncle Bobs train set", 50); 
    second_train ->price = 69; 
    second_train ->next = NULL; 

    struct trainset *third_train; 
    third_train = (struct trainset *)malloc(sizeof(struct trainset)); 
    second_train->next = third_train; 
    strncpy(third_train ->name, "Budha Bread Train", 50); 
    third_train ->price = 169; 
    third_train ->next = NULL; 

    show_list(first_train); 
    return 0; 
} 

void show_list(struct trainset *list) 
{ 
    while(list->next!=NULL) 
    { 
     printf("train set name: %s, Train price: %d\n", list->name, list->price); 
     list = list->next; 
    } 
    printf("train set name: %s, train price: %d", list->name, list->price); 
} 

回答

1

那麼這裏是哪裏的名字是怎麼回事:

strncpy(first_train->name, "Fantasy Train Set", 50); 
... 
strncpy(first_train->name, "Uncle Bobs train set", 50); 

至於是什麼根...這是你的代碼,誰知道。您不需要根節點,只需要記錄第一個節點是什麼。

0

您似乎在重寫first_train-> name。

23  strncpy(first_train->name, "Fantasy Train Set", 50); // see here 
24  first_train->price = 129; 
25  first_train->next = NULL; 
26  struct trainset *second_train; 
27  second_train = (struct trainset *)malloc(sizeof(struct trainset)); 
28  first_train->next = second_train; 
29  strncpy(first_train->name, "Uncle Bobs train set", 50); // and here 

你應該具備的功能和程序做插入和創建操作,我不知道爲什麼你有一個空的根節點,你並不需要做的是,你的根指針可以品脫first_train節點。

你應該這樣做:

list* create(int value) { 
    node = (list*)malloc(sizeof(list)); 
    node->value = value; 
    node->next = NULL; 
} 

list* insert(int value, list* root) { 
    if (!root) { 
     return create(value); 
    } 
    list* aux = root; 
    while(aux->next) { 
     aux = aux->next; 
    } 
    aux->next = create(value); 
    return root; 
} 

此外,在你的循環狀況您有:

while(list->next != NULL) 

你可以把它改寫這樣,你避免了打印的最後一個元素這樣迴路:

while(list){ ... } 

希望這會有所幫助

相關問題