Reputation: 3
I'm new to c++, I'm asked for class work to do a function that takes a doubly linked list and copy it's elements into a singly linked list then returns it, however, I was given this function's declaration only, when I made the function it's either not returning anything or it gives me the error below, I understand the linked list code but I don't understand using a pointer and the returning part, can someone explain this to me? and how to make it work? I'm unable to find explanation to this online, or maybe I am searching the wrong keywords. Any help is appreciated.
template <class T>
SinglyLinkedList<T>* DoublyLinkedList<T>:: Function() {
SinglyLinkedList<T> list1;
DLLnode<T>*p = head;
while (p!=NULL) {
list1.addtoHead(p->value);
p=p->next;
}
return list1;
}
//error: cannot convert ‘SLL<int>’ to ‘SLL<int>*’ in return
Upvotes: 0
Views: 204
Reputation: 87957
1) Using a pointer for this is stupid. But that's what you've been told to do.
2) If you use a pointer then this function will return an address. That's what pointers are. You cannot change that. The trick is to dereference the pointer when you try to print. That way it won't print an address but will instead print what the pointer is pointing at. If you need help with this then post your printing code.
3) Here's how you do it with pointers
template <class T>
SinglyLinkedList<T>* DoublyLinkedList<T>:: Function() {
SinglyLinkedList<T>* list1 = new SinglyLinkedList<T>();
DLLnode<T>*p = head;
while (p!=NULL) {
list1->addtoHead(p->value);
p=p->next;
}
return list1;
}
This is the second occaision in recent days when posters have been told to do something stupid by their university professors. Oh well.
Upvotes: 1