我想使用LinkedList類的duplicate()方法制作鏈接列表的副本。我一直在摸索着如何使這種方法奏效。C++如何創建鏈接列表的副本作爲類對象?
重複的方法需要做一個精確的副本,返回一個指向新列表的指針。我希望能夠在新列表上調用LinkedList方法。我應該返回一個LinkedList指針嗎?或節點指針?我覺得我在這裏完全錯過了一些簡單的東西。
我該如何將新頭節點的位置存儲在LinkedList指針中?
//LinkedList.h
#pragma once
#include<string>
using namespace std;
struct Node {
string nodeData;
Node* nextNode;
};
class LinkedList {
public:
LinkedList();
~LinkedList();
bool insert(string givenData);
bool remove(string givenData);
void print() const;
int count() const;
int find(string givenData) const;
bool removeAll();
LinkedList* duplicate() const;
private:
Node* head;
};
//LinkedList.cpp duplicate() method
LinkedList* LinkedList::duplicate() const {
LinkedList* newList;
Node* newHeadNode = new Node;
Node* newNode = new Node;
newHeadNode->nodeData = head->nodeData;
newHeadNode->nextNode = head->nextNode;
Node* currentNode = head->nextNode;
Node* previousNode = head;
while ((currentNode) && (newNode->nodeData > currentNode->nodeData)) {
previousNode = currentNode;
currentNode = currentNode->nextNode;
newNode->nextNode = previousNode->nextNode;
previousNode->nextNode = newNode;
}
}
我還沒有學過遞歸,所以恐怕這有點高於我的頭。我猜我只需要一個淺拷貝。我對這個概念不太熟悉。通過設置*等於傳入的列表,你是什麼意思? –
任何可以使用遞歸的東西也可以用於循環。如果您對這個概念不滿意,請使用'while'循環。 –