首页 > 解决方案 > 使用运算符 + 就地合并两个排序的链表

问题描述

我一直在尝试在不使用任何额外内存的情况下合并两个排序的链表,并且我试图重载 + 运算符。我想我可能没有很好地理解运算符重载,或者我可能正在弄乱一些我不应该弄乱的指针。我还包括了运算符 << 和 >> 的重载,因为也许我在那里搞砸了一些东西,但我非常怀疑。

#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;
 }

标签: c++ooplinked-list

解决方案


您的 operator + 重载正在返回对您在重载中创建的对象的引用。当你从重载中返回时,对象被销毁,给你留下一个悬空的引用。打开警告,因为您的编译器应该已经检测到。


推荐阅读