[英]How to copy one list onto another via assignment operator overloading? C++
我的頭文件
#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+(const LinkedList &i); //Done
LinkedList operator=(const LinkedList &j);
void makeLists(int n); //Done
void addNode(LinkedList &i);
void removeNode();
void printList();
void printElement();
void sortList();
private:
Node *head;
Node *tail;
int size;
};
#endif
我的功能
LinkedList LinkedList::operator=(LinkedList &j)
{
if (&j != this)
{
Node* temp = j.head;
while (temp->next != nullptr)
{
j.head = j.head->next;
delete temp;
temp = j.head;
}
temp = j.head;
while (temp != nullptr)
{
}
}
return *this;
}
我已經嘗試了幾個小時,但是在第二個while循環中應該做的事情讓我感到困惑。 實際上,我什至不知道我的操作員重載功能是否在遠程上是正確的,但這是我在過去約幾個小時內提出的最佳建議
首先,讓我們修復您已經編寫的代碼。 看起來您已經編寫了完美的“ removeNode()”類方法。 您實際上並未顯示它,但我認為它可以完美地工作。
如果真是這樣,那么刪除該列表的現有節點的動作也是浪費和重復的代碼。 您應該已經將此代碼作為removeNode()方法的一部分進行了編寫。 因此,用一個調用removeNode()的簡單循環替換您在此處編寫的代碼,直到列表為空。
在經歷了這個實驗之后,您應該能夠自己弄清楚,第二個while()循環應該簡單地遍歷另一個列表中的節點,並使用該列表的addNode()方法添加副本。從另一個列表到該列表的每個節點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.