#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;} delete cur;} virtual void insert(int val)=0; void printList() const { listNode* cur=root; while(cur->prev!=nullptr)cur=cur->prev; while(cur!=nullptr){cout<<cur->val<<' ';cur=cur->next;} cout<<endl; } }; 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;} delete cur;} void insert(int v) { if(root->next==nullptr&&root->prev==nullptr){root->val=v;return;} listNode* pre = root; while(pre->prev!=nullptr)pre=pre->prev; if(v<=pre->val){listNode*ins=new listNode();ins->val=v;ins->next=pre;return;} while (pre->next != nullptr && v > pre->val) { pre = pre->next; } listNode*a=pre->next; listNode*ins=new listNode(v, pre, pre->next); ins->prev=pre;ins->next=a; } }; 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;} delete cur;} virtual void insert(int v){ if(root->next==nullptr&&root->prev==nullptr){root->val=v;return;} listNode*pre=root; while(pre->prev!=nullptr)pre=pre->prev; if(v>=pre->val){listNode*ins=new listNode();ins->val=v;ins->next=pre;return;} while(v<pre->val&&pre!=nullptr){pre=pre->next;} listNode*a=pre->next; listNode*ins=new listNode(v, pre, pre->next); ins->prev=pre;ins->next=a; } };输出错误
时间: 2024-02-29 11:57:08 浏览: 94
#include <iostream>
在代码中,构造函数和析构函数中的删除操作存在问题。在析构函数中,应该先删除链表中的节点,再删除root节点,否则会造成内存泄漏。同时,在构造函数中,应该将root节点的prev和next指针设为nullptr,否则会导致插入操作时出现问题。另外,在DescendOrderedList的insert函数中,应该先判断pre是否为nullptr,否则在pre为nullptr时会出现访问pre->val的错误。
阅读全文