【发布时间】:2017-03-29 04:01:37
【问题描述】:
好的,所以我正在尝试通过将它们逐一添加到末尾来创建项目的链接列表,并且我还想打印出结果。
我只展示了我的部分代码(我需要处理的部分),所以请忽略我在这个 sn-p 中没有真正使用的所有库:
#include <string>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
struct Item {
char letter;
Item *next;
};
class List {
public:
List();
void InsertEnd(char key);
void Display();
bool IsEmpty();
void SizeOf();
private:
Item *head;
Item *tail;
int size;
};
List::List() {
head = NULL;
tail = NULL;
size = 0;
}
void List::InsertEnd(char key) {
//new item we're adding to the end
Item* addOn = new Item();
addOn->letter = key;
addOn->next = NULL;
//temporary item to traverse through list
Item* temp = head;
//if list is empty, head and tail both point to it
if ( IsEmpty() ) {
head->next = addOn;
tail->next = addOn;
} else {
//once temp = tail
if (temp->next == NULL) {
tail->next = temp;
temp = addOn;
}
}
//update size of list
SizeOf();
}
void List::Display() {
cout << "Items:" << endl;
for (Item* curr = head->next; curr != NULL; curr = curr->next) {
cout << curr->letter << endl;
}
cout << size << " items." << endl;
}
bool List::IsEmpty() {
if (size == 0)
return true;
else
return false;
}
void List::SizeOf() {
size++;
}
int main() {
List* test = new List;
test->InsertEnd('A');
test->InsertEnd('B');
test->InsertEnd('C');
test->Display();
return 0;
}
它编译得很好,但是当我运行它时,我得到的唯一结果就是“分段错误”。 ???
【问题讨论】:
-
1.您必须发布minimal reproducible example,而不仅仅是您认为错误所在的片段;这是有原因的。 2. 学习使用调试器。调试器回答您的问题比将问题发布到 stackoverflow 更快。
标签: c++ linked-list segmentation-fault