I've been working with linked list and i'm currently trying to make my copyList template function work. It should return the head of the new list. Could someone give me some advice on how to fix it, currently i get no output when i try to print the copied list.
#include <iostream>
#include <list>
#include "node.h"
#include <string>
using namespace std;
template <typename T>
node<T> *copyList(node<T> *front)
{
//set tempHead to front's nodeValue, not sure if this is correct.
node<T> *tempHead = new node<T>(front->nodeValue);
node<T> *temp;
//iterate through list and copy to newly allocated memory
while(front->next != NULL)
{
//create new node
temp = new node<T>;
//set newnode equal to tempHead's next.
temp = tempHead->next;
}
//should return the head of the new list but i think
//there is something wrong here.
node<T> *temp2 = tempHead;
return temp2;
}
template <typename T>
void writeLinkedList(node<T> *front, const string& separator = " ")
{
//front points at first node. curr moves through the list
node<T> *curr;
curr = front;
while (curr != NULL)
{
//output node value and move to the next node
cout << curr->nodeValue << separator;
curr = curr->next;
}
}
int main()
{
//create list and add items to front
node<double> *front = NULL, *p, *newHead = NULL;
int i = 0, n = 0;
p = new node<double>(5.5, front);
front = p;
p = new node<double>(6.7, front);
front = p;
p = new node<double>(15.3, front);
front = p;
p = new node<double>(3.14, front);
front = p;
p = new node<double>(2.718, front);
front = p;
p = new node<double>(15.3, front);
front = p;
p = new node<double>(3.5, front);
front = p;
//print out lists
cout << "List One: " << endl;
writeLinkedList(front, " ");
cout << endl << endl;
cout << "Copied List: " << endl;
newHead = copyList(front);
writeLinkedList(newHead, " ");
cout << endl << endl;
system("PAUSE");
return(0);
}
node class:
template <typename T>
class node
{
public:
T nodeValue; //data held by the node
node<T> *next; //next node in the list
//default contructor with no initial value
node() : next(NULL)
{}
//constructor. initialize nodeValue and next
node(const T& item, node<T> *nextNode = NULL) :
nodeValue(item), next(nextNode)
{}
};