【发布时间】:2012-02-20 22:12:04
【问题描述】:
抱歉,这是一个相当大的问题。我无法让以下 C++ 工作,我总是收到一个错误,即在来自视觉工作室的代码中没有结构/类/联合。我应该按字母顺序将书籍放入链表中,但到目前为止我的插入方法已损坏。
//********************************************************************
// BookList.cpp
//
// Represents a collection of books.
//*******************************************************************
#include "BookList.h"
//----------------------------------------------------------------
// Creates a new Book object and adds it to the end of
// the linked list.
//----------------------------------------------------------------
void BookList::add(Book *newBook) {
BookNode *node = new BookNode(newBook);
BookNode *current;
if (head == NULL)
head = node;
else {
current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = node;
}
}
char *BookList::getBookList(char *list) {
list[0] = '\0';
BookNode *current = head;
while (current != NULL) {
strcat( list, current->book->getBook() );
strcat( list, "\n" );
current = current->next;
}
return list;
}
void BookList::insert(Book *newBook) {
BookNode *node = new BookNode(newBook);
BookNode *current;
if (head == NULL) {
head = node;
}
else {
current = head;
int result = *newBook.compareTo(current->book->getBook());
if (result == -1) {
current->next = node;
}
else {
while (result == 1) {
current = current->next;
result = *newBook.compareTo(current->book->getBook());
}
current->next = node;
}
}
}
//********************************************************************
// BookList.h
//
// Represents a collection of books.
//*******************************************************************
#include "Book.h"
class BookNode {
public:
BookNode() { };
BookNode(Book *theBook) {
book = theBook;
next = NULL;
};
friend class BookList;
private:
Book *book;
BookNode *next;
};
class BookList {
public:
void add(Book *);
char* getBookList(char *);
void delet(Book *);
void insert(Book *);
BookList() {
head = NULL;
};
private:
BookNode *head;
};
#include <cstring>
//********************************************************************
// Book.h
//
// Represents a single book.
//*******************************************************************
class Book {
public:
Book (char *newTitle) {
strcpy( title, newTitle );
}
int compareTo(Book *newBook) {
int compvar;
compvar = strcmp(newBook->getBook(), title);
return compvar;
}
char *getBook() {
return title;
}
private:
char title[81];
};
此代码肯定存在多个问题,因此任何人都可以提供的任何帮助都很棒。提前致谢!
【问题讨论】:
-
它是否给出了一个行号来查看?如果是这样,你能指出源代码中的问题吗?这将有很大帮助。
-
您想要code review,还是有具体问题可以描述?
-
你不应该在没有调试的情况下让它变得这么大。 永远不要添加不起作用的代码。
-
你有一个测试输入用例,你得到什么列表?
-
只挑剔:1) 成员函数定义后没有分号。 2)你在
std::strcpy等几个函数前面忘记了std::。 3) 不要使用strcpy。 4) 不要说81。
标签: c++ sorting linked-list