【发布时间】:2016-03-12 19:30:07
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "Book.h"
int main(int argc, char** argv) {
Book * dummy = newBook("dummy", "dummy", 00000);
printf("%s %s %ld", dummy->title, dummy->author, dummy->ISBN);
dummy->next = NULL;
Book* newishBook = newBook("Foo", "Chris", 1234);
insertToList(newishBook, dummy);
Book* another = newBook("Bar", "Jim", 23344);
insertToList(another, dummy);
Book* yet = newBook("Derp", "Bob", 999);
insertToList(yet, dummy);
displayList(dummy);
searchISBN(999);
return (EXIT_SUCCESS);
}
Book* newBook(char* newTitle, char* newAuthor, long newISBN) {
Book* new_book = malloc(sizeof(Book));
strcpy(new_book->title, newTitle);
strcpy(new_book->author, newAuthor);
new_book->ISBN = newISBN;
return new_book;
}
void insertToList(Book* bookToInsert, Book* dummy){
Book* currentNode = dummy;
Book* temp = malloc(sizeof(Book));
if (currentNode->next == NULL){
currentNode->next = bookToInsert;
printf("Head");
} else {
currentNode= currentNode->next;
while(currentNode->ISBN > bookToInsert->ISBN){
if (bookToInsert ->ISBN < currentNode->ISBN){
// if isbn of current book more than current node, move to next current node
//otherwise add here
printf("Added");
temp->next = currentNode->next;
bookToInsert->next = currentNode->next;
currentNode->next = temp->next;
}
}
}
}
void displayList(Book* dummy){
//start at dummy node-
Book* currentNode = dummy;
bool run = true;
//print until next = null
while(run==true){
if (currentNode->next != NULL){
printf("%s %s %ld \n", currentNode->title, currentNode->author, currentNode->ISBN);
currentNode = currentNode ->next;
} else {
run = false;
}
}
}
该程序旨在创建作为链表节点的书本结构。一本书在头文件Book.h中定义如下:
#ifndef BOOK_H
#define BOOK_H
#ifdef __cplusplus
extern "C" {
#endif
typedef struct book_t {
char title[50];
char author[30];
long ISBN;
struct Book *next;
} Book;
Book* newBook(char* newTitle, char* newAuthor, long newISBN);
#ifdef __cplusplus
}
#endif
#endif /* BOOK_H */
我觉得我的 insertToList 函数快要工作了,但是我看它太错误了导致代码盲,而且我确信它确实存在一些基本错误。目前没有输出 - 只是一个空终端,我相信循环没有正确退出。取消注释 printf 语句“add”和“head”会导致程序无限循环,将“add”输出到终端。
【问题讨论】:
-
newBook()应确保所有字段都已初始化。您不需要在main()中执行dummy->next = NULL;— 这应该由newBook()完成。 -
另外,你的代码编译不干净——你为什么发布不能编译的代码?您(声称)拥有:
typedef struct book_t { …; struct Book *next; } Book;。您没有显示next指针指向的struct Book——它不是struct book_t。因此,您应该收到有关指针类型不匹配的警告。 -
另外,你的循环
while(currentNode->ISBN > bookToInsert->ISBN)永远不会退出,因为条件中使用的变量永远不会在循环内改变。当然,您需要重新考虑您的insertToList功能。 -
temp在insertToList()中的分配令人费解;它看起来可能会泄漏内存。您将要插入bookToInsert,所以不清楚为什么需要temp,除了混淆大家。 -
图书将包含在头文件 (Book.h) 中。我已经从代码中删除了不相关的函数,但我将对其进行编辑以包含我的确切程序,该程序可以编译。
标签: c linked-list singly-linked-list