我一直试图在不使用任何额外内存的情况下合并两个排序的链表,并试图重载+运算符。我想我可能没有很好地理解运算符重载,或者我可能在处理一些不应该处理的指针。我还包括了运算符<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;
}
您的运算符+重载返回对您在重载中创建的对象的引用。当您从重载返回时,对象将被销毁,留下一个悬空引用。打开编译器应该检测到的警告。