【发布时间】:2019-11-08 17:22:15
【问题描述】:
我一直试图在不使用任何额外内存的情况下合并两个排序的链表,并且我试图重载 + 运算符。我想我可能没有很好地理解运算符重载,或者我可能正在弄乱一些我不应该弄乱的指针。 我还包括了运算符 > 的重载,因为也许我在那里搞砸了一些东西,但我非常怀疑。
#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;
}
【问题讨论】:
-
return c;-- 您正在返回对局部变量的引用。未定义的行为。其次,operator +应该返回一个全新的对象,而不是引用。我希望+=返回一个参考。 -
没有一个运算符(在它们的正常原型中)真正适合破坏性地修改第二个操作数。我会推荐一个函数。
-
打开警告,把它们调大,不要忽视它们。编译器错误:源代码在语法上不正确,无法转换为可执行代码。编译器警告意味着源代码在语法上是正确的,可以将其转换为可执行代码,但它可能不会执行您希望它执行的操作。警告是防止运行时错误的第一道防线。
标签: c++ oop linked-list