使用运算符+将两个已排序的链表合并到位
Merge two sorted linked lists in-place using operator +
我一直试图在不使用任何额外内存的情况下合并两个排序的链表,并试图重载+运算符。我想我可能没有很好地理解运算符重载,或者我可能在处理一些不应该处理的指针。我还包括了运算符<lt;和>>因为也许我在那里搞砸了什么,尽管我非常怀疑。
#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;
}
您的运算符+重载返回对您在重载中创建的对象的引用。当您从重载返回时,对象将被销毁,留下一个悬空引用。打开编译器应该检测到的警告。
相关文章:
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 合并两个排序链表时运行时出错
- 在 C++ 中合并两个排序链表
- 在排序链表中插入结构并将其写入二进制文件
- C++:按数字排序链表错误
- 家庭作业的排序链表程序中的分段错误
- 删除已排序链表中的值
- 排序链表-移动节点还是交换数据成员
- 单排序链表-无限循环
- 插入排序链表c++
- 冒泡排序链表C++
- 将元素添加到排序链表C++时出现问题
- 升序排序 - 链表
- 气泡排序链表不排序
- C++ 中的排序链表不会插入
- 删除具有重复相同值的已排序链表中的重复值
- 未排序链表实现检查完毕
- 插入排序链表c++
- c++中从排序链表中删除重复值节点的方法
- 排序链表和addSorted函数问题