Hello,
I created a linked list and implemented a deep copy function. However, the copied list skips the head node in the source list for some reason.
So assume source list contains the following data in their respective nodes:
1 3 6 7 10 312
The copied linked list will be:
3 6 7 10 312
Please tell me what's wrong with it. This is the definition of the deep copy function: OrderedSListT(const OrderedSListT<T>& Source). Its towards the end.
I appreciate any help.
Below is my code:
#ifndef ORDEREDSLISTT_H_
#define ORDEREDSLISTT_H_
#include <new>
template <typename T> class OrderedSListT {
public:
// Give the test harness privileged access:
friend class SListTAuditor;
// Create an empty list object.
OrderedSListT() {
mHead = NULL;
mTail = NULL;
}
// Add the value Data to the list, placing it in the correct location
// relative to the other values in the list (if any). Return true if the
// insertion succeeds (which it will).
bool Insert(const T& Data) {
/*
* Insertion if list is empty
*/
if (mHead == NULL && mTail == NULL) {
SNode* node = new SNode(Data, NULL);
mHead = node;
mTail = node;
return true;
}
else {
/*
* Insertion if new node is before head
*/
if (mHead->mData > Data) {
SNode* node = new SNode(Data, mHead);
mHead = node;
return true;
}
SNode *temp;
temp = mHead;
while (temp->mNext != NULL) {
/*
* Move temporary pointer if data is larger than current pointer
* data
*/
if (temp->mNext->mData < Data) {
temp = temp->mNext;
}
/*
* Insert node in the middle of the list
*/
else if (temp->mNext->mData >= Data) {
SNode* node = new SNode(Data, temp->mNext);
temp->mNext = node;
return true;
}
}
/*
* Insert node at the tail of the list
*/
if (temp->mNext == NULL) {
SNode* node = new SNode(Data, NULL);
temp->mNext = node;
mTail = node;
return true;
}
}
return false;
}
// Delete all values from the list, and restore it to its empty state.
void Clear() {
while (mHead != NULL && mTail != NULL) {
SNode *temp = mHead;
mHead = mHead->mNext;
delete temp;
temp = NULL;
}
if (mHead == NULL) {
mTail = NULL;
}
}
// Provide deep copy support:
OrderedSListT(const OrderedSListT<T>& Source) {
if (Source.mHead != NULL) {
// Source Pointer
SNode *p1 = Source.mHead;
SNode *p2;
SNode *headNode = new SNode(p1->mData, NULL);
p1 = p1->mNext;
bool firstCount = false;
while (p1 != NULL) {
SNode *node = new SNode(p1->mData, NULL);
if (!firstCount) {
headNode->mNext = node;
firstCount = true;
p2 = node;
}
else {
p2->mNext = node;
p2 = p2->mNext;
}
p1 = p1->mNext;
}
p1 = NULL;
p2 = NULL;
}
}
// Destroy all the list nodes.
~OrderedSListT() {
this->Clear();
}
private:
class SNode {
public:
T mData;
// Points to next node in list, if any; otherwise NULL.
SNode* mNext;
// Initialize the node in the obvious way.
SNode(const T& Data, SNode* Next = NULL) {
mData = Data;
mNext = Next;
}
};
// Point to first and last nodes in non-empty list; otherwise NULL.
SNode* mHead;
SNode* mTail;
};
// Implementations of list member functions should go here:
// End of member implementations
#endif