【问题标题】:How to concatenate two singly linked lists via operator overloading? [duplicate]如何通过运算符重载连接两个单链表? [复制]
【发布时间】:2016-04-09 21:53:49
【问题描述】:

这是我的头文件

#ifndef LINKEDLIST_H
#define LINKEDLIST_H

#include <iostream>
#include <string>
using namespace std;

class Node
{
    friend class LinkedList;

public:
    Node(string& name, int num) :studentName(name), RUID(num)
    {
        this->next = NULL;
    }

private:
    string studentName;
    int RUID;
    Node *next;
};

class LinkedList
{
public:
    LinkedList();
    ~LinkedList();

    LinkedList& operator+(LinkedList &i);
    //LinkedList operator=();

    void makeLists(int n);
    void addNode(LinkedList &i);
    void removeNode();
    void printList();
    void printElement();
    void sortList();

private:
    Node *head;
    Node *tail;
    int size;
};

#endif

...这是我的 operator+ 函数

LinkedList& LinkedList::operator+(LinkedList &i)
{
    LinkedList tohma;
    tohma = *this;
    tohma += i;
    return tohma;
}

我收到 += 运算符的错误消息,但我不知道应该如何做不同的事情。我觉得我很接近,但也许我犯了一个逻辑错误?

我们将不胜感激任何和所有的帮助

【问题讨论】:

  • 它是operator+,而不是+=(甚至没有定义),它通过引用返回一个本地 - 错误。按值返回。
  • 抱歉,我的意思是“tohma += i”处有一条错误消息。我的坏

标签: c++ linked-list operator-overloading singly-linked-list


【解决方案1】:

通常,operator+LinkedList 的结构如下:

LinkedList operator+(const LinkedList& _list) {

    // ptr to list to return, initialised with this
    LinkedList* ret_list = this;

    // temporary node ptr for iterating through _list
    Node* temp = _list.head;

    // loop through contents of _list
    while (temp != nullptr) {
        // insert data from _list to ret_list
        ret_list->insert(temp->data);  
        // ^= this will need to be changed for your specific list fields and insert methods
        temp = temp->next;
    }

    return &ret_list;

}

至于operator+=,也有类似的逻辑:

LinkedList& operator+=(const LinkedList& _list) {

    Node* temp = _list.head;

    while (temp != nullptr) {
        insert(temp->data);
        temp = temp->next;
    }        

    return *this;

}

我在这里可能有问题,因为它已经很晚了,但它应该是准确的。

【讨论】:

  • 这绝对有帮助。我现在只需要插入我的两个数据
  • 谢谢你,我的做法和你有点不同,但你的帮助很大
【解决方案2】:
LinkedList LinkedList::operator+(const LinkedList &i)
{
    LinkedList* tohma = this;
    Node* temp = i.head;

    tohma->tail->next = temp;

    return *tohma;
}

由于我已经为我的第一个列表保存了尾节点,我可以使用它来将它与第二个列表连接

【讨论】:

    猜你喜欢
    • 2021-09-04
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2012-06-09
    相关资源
    最近更新 更多