我为链接列表的重载 = 运算符编写了一些代码,但由于某种原因它没有做任何事情,我不明白为什么。
包含链表的类称为 String,结构 ListNode 是节点本身。
列表节点:
struct ListNode
{
char info;
ListNode * next;
ListNode(char newInfo, ListNode * newNext)
: info( newInfo ), next( newNext )
{
}
};
字符串:
class String {
private:
ListNode* head;
public:
String( const char * s = "");
String( const String & s );
String operator = ( const String & s );
~String();
}
ostream & operator << ( ostream & out, String& str );
istream & operator >> ( istream & in, String & str );
字符串.cpp:
String::String( const char * s) {
if (s == "") {
head = NULL;
return;
}
ListNode* newNode = new ListNode(s[0], NULL);
head = newNode;
ListNode* current = head;
for (int i = 1; s[i] != 0; current = current->next) {
current->next = new ListNode(s[i], NULL);
++i;
}
}
String::String(const String& s ) {
ListNode* current = new ListNode((s.head)->info, NULL); //make all next's null just in case
head = current;
for(ListNode* sstart = s.head->next; sstart != NULL; sstart = sstart->next) {
current->next = new ListNode(sstart->info, NULL);
current = current->next;
}
}
//RETURN STRING BY REFERENCE OR COPY CONSTRUCTOR IS CALLED
String& String::operator = ( const String & s ) {
ListNode* start = head;
ListNode* tmp;
while(start != NULL) {
tmp = start->next;
delete start;
start = tmp;
}
head = NULL;
if (s.head == NULL)
return *this;
ListNode* current = new ListNode((s.head)->info, NULL); //make all next's null just in case
head = current;
for(ListNode* sstart = s.head->next; sstart != NULL; sstart = sstart->next) {
current->next = new ListNode(sstart->info, NULL);
current = current->next;
}
return *this;
}
String::~String() {
ListNode* nextNode = head;
ListNode* tmp;
while(nextNode) {
tmp = nextNode->next;
delete nextNode;
nextNode = tmp;
}
}
ostream & operator << ( ostream & out, String& str) {
for (int i = 0; i < str.length(); ++i) {
out << str[i];
}
return out;
}
istream & operator >> ( istream & in, String & str ) {
int len = in.gcount();
char* buf = new char[len];
char inChar;
for(int i = 0; in >> inChar; ++i) {
buf[i] = inChar;
}
String tmp(buf);
str = tmp;
}
在第一个循环中,我删除了 head 指向的链表。在那之后,我将 head 设置为 NULL 以应对 s 根本不包含任何内容的情况。如果不是,那么,我将 current 设置为 s 中第一个 ListNode 的拷贝,并将 current 存储在 head 中(如果我使用 head 遍历,那么我将丢失指向列表开头的指针)。最后,我的第二个循环会将 s 的其余部分“附加”到当前。
当我运行我的代码时,没有任何反应。我的终端将打印出一个空行,然后什么也没有,这向我暗示我可能会在某个地方无限大。我的代码有什么问题?
编辑:更改了链表的删除,问题仍然存在。
最佳答案
您通过访问此代码段中已删除的对象(自 tmp == start 以来)导致未定义的行为:
tmp = start;
delete start;
start = tmp->next;
可能还有其他问题,但首先要解决它。例如,您可以在删除之前将下一个指针存储在临时变量中:
tmp = start->next;
delete start;
start = tmp;
关于c++ - 链表赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21641507/