I would just create an
insert() function for doubly linked list class and have this while loop in your copy function:
1 2 3 4 5 6 7 8
|
//This code traverses the singly linked list
//and copies into doubly linked list.
//The problem is then how to get access to p.
while(p != nullptr)
{
doublyLinkedList.insert( p->element );
p = p->getNextPtr();
}
|
Where
p pointer keeps track of current element in singly linked list.
getNextPtr() is a function that returns a pointer to the next element in the singly linked list, so you can update copying over the next element to your doubly linked list.
Where to implement your copy function?
You can make a doubly linked list constructor that takes in a singly linked list parameter and copies over the singly linked list elements.
Or you can make a non-constructor method that takes a singly linked list as parameter and copies the data over.
How to get singly linked list's head pointer 'p'?
To do all this, you can make an iterator that passes through your elements since your singly linked list pointer is most likely private. An iterator is a class that points to your elements and is publicly accessibly. You can nest it in your class or make it separate. The point of an iterator is to give clients access to the elements of your data structure. In this case, instead of using p, you would use the iterator.
Here is a tutorial on iterators:
http://www.cprogramming.com/tutorial/stl/iterators.html
Sample iterator class nested within a list class:
http://users.cis.fiu.edu/~weiss/dsaa_c++4/code/List.h
Unless doubly linked list is private or protected inheritance of singly linked list, in which case doubly linked list can access the private or protected pointers of singly linked list class. Iterators may be daunting for beginners, so I would suggest using this exercise to learn inheritance instead.