gpt4 book ai didi

c++ - 链表段错误 11

转载 作者:行者123 更新时间:2023-11-28 05:28:06 25 4
gpt4 key购买 nike

<分区>

我的一项作业有问题。我需要做一个链表连接,但是在重新定义 operator+ 之后,我有段错误。这是代码:

在 main.cpp 中:

case CONCAT:
do
{
std::cout << "Which two list do you want to concat?(1-3) ";
std::cin >> s;
std::cin >> g;
selectedlist =atoi(s.c_str());
selectedlist2 =atoi(g.c_str());
} while ((
selectedlist== 0 &&
s != "0" &&
(selectedlist > 3 || selectedlist < 1)
) &&
(
selectedlist2== 0 &&
g != "0" &&
(selectedlist2 > 3 || selectedlist2 < 1)
)
);
Lista[selectedlist-1]+Lista[selectedlist2-1];
std::cout<<"Ready";

break;

在头文件中:

class lista
{
public:
enum Exceptions{EMPTY};
lista() : first(NULL),last(NULL),current(NULL){ first = new Elem(0,0);}
virtual ~lista();
lista(const lista& s);
int Current() const {return current->Adat;}
void First() {current = first->next;}
bool End() const {return current==NULL;}
void Next() {current = current->next;}
void Vegere(int e);
void Elejerol();
bool Urese();
int Eleje();
friend std::ostream& operator<<(std::ostream& s, const lista& a);
friend lista operator+(lista& a, lista& b);

private:
struct Elem{
int Adat;
Elem* next;
Elem(int c, Elem* n): Adat(c), next(n){};
};
Elem* first;
Elem* last;
Elem* current;
};

在 lista.cpp 中:

lista operator+(lista& a, lista& b)
{
if(b.first->next!=NULL && a.first->next!=NULL)
{
a.last->next = b.first->next;
a.last = b.last;
b.first = new lista::Elem(0,0);
b.last = NULL;
b.current = NULL;
}
else
{
throw lista::EMPTY;
}
return a;
}

void lista::Vegere(int e) {
Elem* p = new Elem(e,0);
if(last==NULL) {
first -> next = p;
last = p;
}
else {
last -> next = p;
last = p;
}
}

它提示,所有其他功能(清空、添加数字等)工作正常。我做错了什么?

void lista::Vegere(int e) 
{
Elem* p = new Elem(e,0);
if(last==NULL)
{
first -> next = p; last = p;
}
else
{
last -> next = p; last = p;
}
}

析构函数:

lista::~lista()
{
Elem *p, *v;
p = first;
v = first -> next;
while( v!=NULL)
{
delete p;
p = v;
v = v -> next;
}
delete p;
}

我想通了。我没有在这里发布这部分代码,但经过一些调试后,我得到了它。

这里是错误:

    lista::lista(const lista& s){
if(s.first->next==NULL)
{
first->next = last = NULL;
}
else
{
Elem* q = new Elem(s.first->Adat,NULL);
first = q;
for(Elem* p=s.first->next;p!=NULL;p=p->next)
{
q = new Elem(p->Adat,NULL);
q->next = q;
}
last = q;
}

current = first;

THIS PART is the error:
[
while(current!=NULL && current->Adat!=s.current->Adat)
{
current=current->next;
}
]
}

我刚刚删除了它,它可以正常工作。 :)

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com