我想使用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'循环。 –