I'm trying to make a copy of a linked List using the duplicate() method of the LinkedList class. I've been scratching my head all day about how to make this method work.
The duplicate method needs to make an exact copy of the list, returning a pointer to the new list. I want to be able to call LinkedList methods on the new list. Should I be returning a LinkedList pointer? or a Node pointer? I feel like I'm totally missing something easy here.
How would I even store the location of the new head node in the LinkedList pointer?
//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;
}
}