c++中双链表的未处理异常

  • 本文关键字:未处理 异常 链表 c++ c++
  • 更新时间 :
  • 英文 :


我用c++创建了一个双链表。如果我在链表的开头插入一个节点或者在链表的末尾插入一个节点,一切都很顺利;但是,当我在开头插入一个节点,然后尝试在末尾插入一个节点时,我得到一个空指针错误!

下面是代码,问题在InserAtEnd函数

#include <iostream>
using namespace std;
struct Node {
int data;
Node* prev;
Node* next;
};
struct MyList {
Node* head;
Node* tail;
};
bool IsEmpty(MyList list) {
if (list.head == nullptr) return true;
else return false;
}
void Insert(MyList& list, int data) {
Node* node = new Node();
node->data = data;
node->prev = nullptr;
node->next = list.head;   //node->next points to NULL
if (list.head == nullptr) {
list.head = node;
node->prev = nullptr;
}
else {
//insert the new node at the beginning of the list
list.head->prev = node;
list.head = node;
node->prev = nullptr;
}
}
// Insert node at end of list
void InsertAtEnd(MyList& list, int data) {
Node* node = new Node();
node->data = data;
node->next = nullptr;
node->prev = nullptr;
if (list.head == nullptr) { // Empty list
list.head = node;
list.tail = node;
}
else {
list.tail->next = node;
node->prev = list.tail;
list.tail = node;
}
}

//Traverse the list from the head
void PrintAll(const MyList& list) {
Node* temp = list.head;
if (temp == nullptr) {
cout << "list is empty" << endl;
}
else {
while (temp != nullptr)
{
cout << temp->data << endl;
temp = temp->next;
}
cout << "*************************************" << endl;
}
}
Node* Search(const MyList& list, int key) {
Node* temp = list.head;
while (temp != nullptr && temp->data != key)
{
temp = temp->next;
}
return temp;
}
void Delete(MyList& list, int key) {
Node* temp = Search(list, key); //call search() 
if (temp != nullptr)
{
if (temp->prev != nullptr)
{
temp->prev->next = temp->next;
}
else
{
list.head = temp->next;
}
if (temp->next != nullptr)
{
temp->next->prev = temp->prev;
}
}
}
int main() {
MyList list;
list.head = nullptr;    //initialize the linked-list
list.tail = nullptr;
if (IsEmpty(list)) 
cout << "List is empty" << endl;

Insert(list, 10);
PrintAll(list);
/*
Insert(list, 20);
Insert(list, 30);
Insert(list, 40);
*/
// Insert at end
cout << "Now insert at end" << endl;
InsertAtEnd(list, 70);
InsertAtEnd(list, 45);
InsertAtEnd(list, 59);
InsertAtEnd(list, 12);
InsertAtEnd(list, 33);
PrintAll(list);

/*
int x = 24;
Node* result = Search(list, x);
if (result == nullptr) cout << "Cannot find " << x << endl;
else cout << "Found " << result->data << endl;
Delete(list, 200);
PrintAll(list);
Delete(list, 10);
PrintAll(list);
Delete(list, 40);
PrintAll(list);
Delete(list, 20);
PrintAll(list);
Delete(list, 30);
PrintAll(list);
*/
return 0;
}

问题出在InserAtEnd函数

你怎么知道?

事实上,问题不在于InserAtEnd,而在于Insert:

您从未设置过list.tail

提示:使用Node **tail = &head;来获得更有效的MyList,并添加成员初始化式和构造函数。

这是带有类的c++。使用成员函数

相关内容

最新更新