#include <iostream> #include "listnode.h" using namespace std; struct listNode { listNode * prev, * next; int val; listNode(): val(0), prev(nullptr), next(nullptr){} listNode(int v, listNode *p, listNode *n): val(v), prev(p), next(n) { if (prev != nullptr) prev->next = this; if (next != nullptr) next->prev = this; } }; class OrderedList { protected: listNode * root; public: OrderedList(){root=new listNode();} ~OrderedList(){ listNode* cur=root; if(cur->prev!=nullptr)cur=cur->prev; if(cur!=nullptr){listNode*tmp=cur;cur=cur->next;delete tmp;}} virtual void insert(int val)=0; void printList() const { listNode* cur=root; if(cur->prev!=nullptr)cur=cur->prev; if(cur!=nullptr){cout<<cur->val<<' ';cur=cur->next;} } }; class AscendOrderedList:public OrderedList { public: AscendOrderedList(){root=new listNode();} ~AscendOrderedList(){ listNode* cur=root; if(cur->prev!=nullptr)cur=cur->prev; if(cur!=nullptr){listNode*tmp=cur;cur=cur->next;delete tmp;}} virtual void insert(int v){ listNode*pre=root; while(v>pre->val&&pre!=nullptr){pre=pre->next;} listNode*ins=new listNode(v, pre,pre->next); pre->next=ins; ins->next->prev=ins; } }; class DescendOrderedList:public OrderedList { public: DescendOrderedList(){root=new listNode();} ~DescendOrderedList(){ listNode* cur=root; if(cur->prev!=nullptr)cur=cur->prev; if(cur!=nullptr){listNode*tmp=cur;cur=cur->next;delete tmp;}} virtual void insert(int v){ listNode*pre=root; while(v<pre->val&&pre!=nullptr){pre=pre->next;} listNode*ins=new listNode(v, pre, pre->next); pre->next=ins; ins->next->prev=ins; } }为什么运行崩溃
时间: 2024-02-28 18:56:34 浏览: 75
这段代码中可能会有多个问题,具体原因需要根据您的输入、程序运行环境以及错误提示等来确定。以下是一些可能的问题和建议:
1. 在 `listNode` 的构造函数中,需要判断 `prev` 和 `next` 是否为空指针,才能为它们的 `prev` 和 `next` 成员变量赋值。修改代码如下:
```
listNode(int v, listNode* p, listNode* n) : val(v), prev(p), next(n) {
if (prev != nullptr) {
prev->next = this;
}
if (next != nullptr) {
next->prev = this;
}
}
```
2. 在 `OrderedList` 和其子类的析构函数中,需要循环删除链表中的所有节点。修改代码如下:
```
~OrderedList() {
listNode* cur = root;
while (cur->next != nullptr) {
cur = cur->next;
delete cur->prev;
}
delete cur;
}
~AscendOrderedList() {
listNode* cur = root;
while (cur->next != nullptr) {
cur = cur->next;
delete cur->prev;
}
delete cur;
}
~DescendOrderedList() {
listNode* cur = root;
while (cur->next != nullptr) {
cur = cur->next;
delete cur->prev;
}
delete cur;
}
```
3. 在 `AscendOrderedList` 和 `DescendOrderedList` 的 `insert()` 方法中,需要先判断当前节点是否为空指针,否则会出现访问空指针的错误。修改代码如下:
```
void insert(int v) {
listNode* pre = root;
while (pre->next != nullptr && v > pre->val) {
pre = pre->next;
}
listNode* ins = new listNode(v, pre, pre->next);
pre->next = ins;
if (ins->next != nullptr) {
ins->next->prev = ins;
}
}
```
```
void insert(int v) {
listNode* pre = root;
while (pre->next != nullptr && v < pre->val) {
pre = pre->next;
}
listNode* ins = new listNode(v, pre, pre->next);
pre->next = ins;
if (ins->next != nullptr) {
ins->next->prev = ins;
}
}
```
以上是可能的问题和建议,如果您还有其他问题或者需要更多帮助,请提供更多详细的信息和错误提示,以便我们更好地帮助您解决问题。
阅读全文