在C中使用链表

我是链接列表主题的新手,我刚刚使用链表创建了我的第一个程序,问题是它没有将任何数据保存到结构中。 它运行正常,没有错误,但是在打印时没有显示数据。 这是我的代码。

#include  #include  #include  struct node { int nID; char chTitle; struct node* next; }; void addList(struct node *head); void printList(struct node *head); int checkID(struct node *head, int t); int main(int argc, const char * argv[]) { int nInput; struct node *head = NULL; while (1) { printf("\n\t\t~~MENU~~\n"); printf("1. Add a new book\n"); printf("2. Print all data\n"); printf("3. Exit\n"); printf("Make your selection: "); scanf("%d", &nInput); switch (nInput) { case 1: addList(head); break; case 2: printList(head); break; case 3: printf("\nGoodby!!! Thanks for using the program\n"); exit(1); break; default: printf("\n\t\t~~Invalid Input~~\n"); break; } } return 0; } void addList(struct node *head) { int bookId; // Used to store the BOOK ISBN so it can be checked if it already exist struct node *temp; temp = (struct node *)malloc(sizeof(struct node)); printf("\n Enter Book Details\n"); printf("Enter book ISBN: "); scanf("%d", &bookId); int bInd = checkID(head, bookId); if (bInd == 0) { printf("Enter title: "); scanf("%s", &temp->chTitle); temp->next = head; head = temp; } else { printf("\nSorry another book using that id!\n" ); } } void printList(struct node* head) { while (head != NULL) { printf("%s", &head->chTitle); head = head->next; } } int checkID(struct node *head, int t) { head = NULL; while (head != NULL) { if (head->nID == t) return 1; head = head->next; } return 0; } 

一个问题就在这里:

 void addList(struct node *head) 

addList()获取头指针的COPY,因此当您在此函数中修改它时,您只修改该本地副本。 调用者的版本未被修改。 解决此问题的一种方法是使用双指针:

 void addList(struct node **head) { int bookId; // Used to store the BOOK ISBN so it can be checked if it already exist struct node *temp; temp = (struct node *)malloc(sizeof(struct node)); printf("\n Enter Book Details\n"); printf("Enter book ISBN: "); scanf("%d", &bookId); int bInd = checkID(*head, bookId); if (bInd == 0) { printf("Enter title: "); scanf("%s", &temp->chTitle); temp->next = *head; *head = temp; } else { printf("\nSorry another book using that id!\n" ); } } 

然后你的来电者也必须改变:

 addList(&head); 

另外,正如@ 5gon12eder所提到的,一个char只包含一个字符。 你需要一个char数组来保存你的标题:

 struct node { int nID; char chTitle[100]; /* or how ever long your title can be */ struct node* next; }; 

您可以像这样更改addList标头,

void addList(struct node *&head)

这里head成为对node类型指针的引用。 因此,当您在addList中修改head时,它将反映在原始列表中。