
[英]Inserting a single element in a linked list gives a segmentation fault - C++
[英]Segmentation fault when inserting at the end of a linked list C++
好的,所以我试图通过逐项添加到末尾来创建项目的链接列表,并且我也想打印出结果。
我只显示我的部分代码(需要处理的部分),因此请忽略此代码段中我没有真正使用的所有库:
#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;
}
它可以很好地编译,但是当我运行它时,我唯一得到的就是“分段错误”。 ???
如果列表为空,则head->next
将为NULL,但是您说head->next = addOn;
。 不应该是head = addOn;
?
实际上,这整个代码块都是垃圾:
if ( IsEmpty() ) {
// head and tail are both null so both of these lines
// invoke undefined behavior (you cant say NULL->field = something)
head->next = addOn;
tail->next = addOn;
} else {
//once temp = tail
// temp = head. Shouldn't you just be putting "addOn" as the next item
// in the list after tail? What if temp->next != NULL?
if (temp->next == NULL) {
// tail->next = head (because temp == head). That makes no sense.
tail->next = temp;
// So some temp variable = addOn? addOn doesn't actually go into the list?
// Thats a memory leak right there.
temp = addOn;
}
}
用伪代码,您想要的是这样的:
if (IsEmpty())
{
head = addOn;
tail = addOn;
}
else
{
// special case when 1 item in the list (i.e. head == tail)
if (head == tail)
{
// new item comes after head
head->next = addOn;
}
else
{
// new item comes after tail
tail->next = addOn;
}
// tail is now the item just added.
tail = addOn;
}
我建议您一步一步进入调试器,并在崩溃时准确查看哪个值为空。 调试器将向您显示代码每一步的每个值。 我已经进行了30多年的编程工作,每天我都会一步步完成代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.