【发布时间】:2016-10-29 13:52:00
【问题描述】:
下面的代码正确插入节点,但是 我有一个问题,当尝试打印列表时,程序不幸停止工作。 错误消息是:您的项目已停止工作。 这是我的代码:
#include <iostream>
#include <string>
using namespace std;
typedef struct st {
string data;
int ISBN;
string Title;
string Author;
int publishedyear;
bool borrow;
st* next;
} NODE;
NODE* add(NODE* head, int isbn)
{
NODE *p1, *p2;
NODE* n;
n = new NODE;
n->ISBN = isbn;
if (head == NULL) {
head = n;
return head;
}
if (n->ISBN < head->ISBN) {
n->next = head;
head = n;
return head;
}
p1 = p2 = head;
while (p2 != NULL) {
if (n->ISBN < p2->ISBN) {
n->next = p2;
p1->next = n;
return head;
}
else {
p1 = p2;
p2 = p2->next;
}
}
n->next = p2;
p1->next = n;
return head;
}
void print(NODE* head)
{
NODE* p;
p = head;
if (head == NULL) {
cout << "empty list" << endl;
}
while (p != NULL) {
cout << "Book ISBN Is : " << p->ISBN << endl;
p = p->next;
}
}
void main()
{
// cout << "hi";
NODE* head;
head = NULL;
string op;
int isbn;
cout << "Enter the opertion in the following format : op , ISBN" << endl;
while (1) {
cin >> op;
if (op == "add") {
cin >> isbn;
if (op == "add") {
head = add(head, isbn);
cout << "book with thie ISBN code " << isbn << " is added successfuly."
<< endl;
}
}
else if (op == "print") {
print(head);
}
else {
cout << "Enter vaild operation! ." << endl;
}
}
}
有什么建议吗?
【问题讨论】:
-
奥拉夫以光速移动。
-
这是 C++,而不是 C。但是您使用 C 编码 style,这在 C++ 中是一种不好的做法,特别适用于这个应用程序。
-
所以。如何解决问题?
-
崩溃使调试变得容易。在调试器中运行几乎可以肯定随您的开发环境附带的程序,并在调试器因崩溃而停止时检查程序状态。如果您无法从中找出问题所在,请将状态添加到问题中。
-
阅读How to Ask 并关注它。正如@user4581301 所写:使用调试器了解更多信息。还要正确地格式化和缩进你的代码。
标签: c++ list linked-list