c/c++语言开发共享在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("ntt~~MENU~~n"); printf("1. Add a new bookn"); printf("2. Print all datan"); printf("3. Exitn"); 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 programn"); exit(1); break; default: printf("ntt~~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 Detailsn"); 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 Detailsn"); 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时,它将反映在原始列表中。

      以上就是c/c++开发分享在C中使用链表相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/522213.html

      (0)
      上一篇 2020年12月9日
      下一篇 2020年12月9日

      精彩推荐