c++ - 使用运算符 + 就地合并两个排序的链表
问题描述
我一直在尝试在不使用任何额外内存的情况下合并两个排序的链表,并且我试图重载 + 运算符。我想我可能没有很好地理解运算符重载,或者我可能正在弄乱一些我不应该弄乱的指针。我还包括了运算符 << 和 >> 的重载,因为也许我在那里搞砸了一些东西,但我非常怀疑。
#include <iostream>
using namespace std;
struct node{
int value;
node* next;
};
class LinkedList{
public:
node *head, *tail;
LinkedList();
void AddElement(int);
LinkedList& operator + (const LinkedList&);
friend ostream& operator << (ostream&, const LinkedList&);
friend istream& operator >> (istream&, LinkedList&);
};
LinkedList& LinkedList::operator + (const LinkedList& b){
LinkedList c;
node* temp_head;
node* temp_a = head;
node* temp_b = b.head;
if(temp_a == NULL){
temp_head = temp_b;
}
if(temp_b == NULL){
temp_head = temp_a;
}
if(temp_a->value < temp_b->value){
temp_head = temp_a;
}else{
temp_head = temp_b;
temp_b = temp_a;
temp_a = temp_head;
}
while(temp_a->next != NULL){
if(temp_a->next->value > temp_b->value){
node* temp = temp_b;
temp_b = temp_a->next;
temp_a->next = temp;
}
temp_a = temp_a->next;
}
temp_a->next = temp_b;
while(temp_b->next != NULL){
temp_b = temp_b->next;
}
c.head = temp_head;
c.tail = temp_b;
cout << c;
return c;
}
LinkedList::LinkedList(){
head = NULL;
tail = NULL;
}
istream& operator >> (istream& in, LinkedList& l){
cout << "New List" << endl;
cout << "Number of elements in the list:" << endl;
int n;
cin >> n;
for(int i = 0; i < n; i++){
int new_value;
cin >> new_value;
l.AddElement(new_value);
}
return in;
}
ostream& operator << (ostream& out, const LinkedList& l){
node* p = l.head;
while(p){
cout << p->value << " ";
p = p->next;
}
cout << endl;
return out;
}
void LinkedList::AddElement(int new_value){
// function that adds a new element at the end of the list
node* q = new node;
q->value = new_value;
q->next = NULL;
if(head == NULL){
head = q;
tail = q;
q = NULL;
}else{
tail->next = q;
tail = q;
}
}
int main()
{
LinkedList a, b;
cout << "List 1." << endl;
cin >> a;
cout << a;
cout << "List 2." << endl;
cin >> b;
cout << b;
cout << (a + b);
return 0;
}
解决方案
您的 operator + 重载正在返回对您在重载中创建的对象的引用。当你从重载中返回时,对象被销毁,给你留下一个悬空的引用。打开警告,因为您的编译器应该已经检测到。
推荐阅读
- performance - 如何为表格数据实施快速梯度符号攻击?
- javascript - 此处映射 API 未在 bootstrap 5 模式中显示
- typescript - 使用动态键和特定键定义接口或类型
- python - 如何验证手机号码是否正确?
- javascript - 防止单击时隐藏元素
- amazon-web-services - 使用 AWS 负载均衡器的证书颁发机构 SSL
- pytorch - 不同设置下预训练 ditilBert 模型的性能差异
- android - Recyclerview 中提升的 CardView 项目逐渐获得更多阴影
- kivy - 如何在 Kivy 或 KivyMD 中创建类似快照的按钮?
- c - 使用 select() 与 pipe() 和 fork() 结合使用的奇怪行为