这是大学的一项编程作业。主程序是教授给我的。我必须创建dlist.h。调试时,会收到此分段错误。我也有这样的想法:
get (dl=..., val=<error reading variable>) at dlist.h:37#include <iostream>
#include <exception>
struct DListElem { //element of the list
int info;
DListElem * prev;
DListElem * next;
};
struct DList{ //just stores pointers to first and last elements of the list
DListElem * first;
DListElem * last;
};
void initializeDList(DList & dl){ //Iinitializes dl as empty list
dl.first = nullptr;
dl.last = nullptr;
}
void put(DList& dl, int val){ //insert a new element with value val at the beginning of the list.
DListElem* front_elem = new DListElem;
front_elem ->info = val;
front_elem -> prev = nullptr;
front_elem -> next = dl.first;
dl.first = front_elem;
if(dl.last==NULL) dl.last=dl.first;
}
bool get(DList& dl, int& val){
/*Removes an item (if possible) from the end of the list. The value of the last
element is returned by the val parameter, the memory for the list element
is released. The return value indicates whether an item could be retrieved,
i.e. it returns false for an empty list and true otherwise.*/
if(dl.last==nullptr) return false;
if (dl.first==dl.last){ //if there is only 1 element
val = dl.last -> info;
DListElem* buffer = new DListElem;
buffer = dl.last;
dl.last = nullptr;
dl.first = nullptr;
delete (buffer);
}
else{
val = dl.last -> info;
DListElem* buffer = new DListElem;
buffer = dl.last;
dl.last = dl.last -> prev;
dl.last -> next = nullptr; //this part seems to still be the problem
delete (buffer);
};
return true;
}这是我的主要节目:
#include <iostream>
#include "dlist.h"
using namespace std;
int main (int argc, char *argv[]) {
DList queue;
initializeDList (queue);插入5个值
for (int i = 1; i <= 5; i++) {
cout << "put: " << 10 * i << endl;
put (queue, 10 * i);
} 移除3个值并将它们打印到控制台。
for (int j = 1; j <= 3; j++){
int value;
if (get (queue, value))
cout << " get: " << value << endl;
}我想这些是必要的:
cin.sync ();
cin.get ();
return 0;
}发布于 2021-11-04 21:17:07
好的,问题是函数put();我没有很好地实现它,它只产生了一个链接列表;因此,dl.last在函数get()中变为空,表达式dl.last -> next = nullptr;是问题的原因;
--这是更正的put()
put (DList & dl, int val)
{ //insert a new element with value val at the beginning of the list.
DListElem *front_elem = new DListElem;
front_elem->info = val;
front_elem->prev = nullptr;
front_elem->next = dl.first;
if (dl.first != nullptr && dl.first->next == nullptr)
dl.last = dl.first;
if (dl.first != nullptr)
dl.first->prev = front_elem;
dl.first = front_elem;
}https://stackoverflow.com/questions/69840659
复制相似问题