#include<iostream>
using namespace std;
#define NULL 0
template <typename T>
class DoublyList;
template <typename T>
class Node
{
friend class DoublyList<T>;
public:
Node()
{next = this; prev = this;}
Node(const T& data, Node<T> *next = NULL, Node<T> *prev)
{this ->data = data; this ->next = next;
this ->prev = prev;}
private:
T data;
Node<T> *next;
Node<T> *prev;
};
template <typename T>
class DoublyList
{
public:
DoublyList();
DoublyList(T someArray[], T arraySize);
~DoublyList();
Node<T> *add(Node<T> *insert, const T& data);
void mergeList(DoublyList<T>& listA);
void print();
private:
Node<T> *header;
int size; // number of data nodes in list
};
// Default constructor for creating empty linked list
template<typename T>
DoublyList<T>::DoublyList()
{
header = new Node<T>();
size = 0;
}
template<typename T>
DoublyList<T>::DoublyList(T someArray[], T arraySize)
{
header = new Node<T>();
size = arrSize;
for (int i = 0; i < size; i++)
{
add(someArray[i], arraySize);
}
}
// This is a destructor
template<typename T>
DoublyList<T>::~DoublyList()
{
while (header->next != header)
{
Node* next = header ->next;
header = next;
}
delete header;
}
template<typename T>
Node<T> *DoublyList<T>::add(Node<T> *insert, const T& data)
{
Node<T> *prevPtr;
Node<T> *newPtr;
prevPtr = add ->prev;
newPtr = new Node<T>(data, add, prevPtr);
size++;
add ->prev = prevPtr->next = newPtr;
return newPtr;
}
// This function perform a sorted merge between the calling object list and the passed in listA
template<typename T>
void DoublyList<T>::mergeList(DoublyList<T> &listA)
{
DoublyList<T> *result = NULL; // build the answer here
DoublyList<T> *current = *listA; //iterate over the original list
DoublyList<T> *next;
while(current != NULL)
{
next = current ->next;
insert(&result, current);
current = next;
}
*listA = result;
}
// This function print the values of each node in the list. If the list is empty it prints an error message
template<typename T>
void DoublyList<T>::print()
{
if(header->next = header)
{
cout<<"list is empty now"<<endl;
}
I am not sure how can I print the value of each node here?
}
Here is the main function
int main()
{
int array1[] = {2,5,7};
int array2[] = {1,3,4,6};
int array1Size = sizeof(array1)/sizeof(int);
int array2Size = sizeof(array2)/sizeof(int);
DoublyList<int> list1(array1, array1Size);
DoublyList<int> list2(array2, arraySize);
DoublyList<int> list3;
list1.mergeList(list2);
list3.print();
}
It should print :
1 2 3 4 5 6 7
list is empty now
Thanks for any help.
MOD EDIT: Edited title to be more descriptive
This post has been edited by KYA: 01 December 2009 - 05:36 PM

New Topic/Question
Reply



MultiQuote




|