I've been trying to create an ordered double linked list and then print it out forwards and backwards using recursion. I don't know if I'm adding nodes to the linked list incorrectly or if my problem is in my print functions.
Main
int main() {
ifstream addData;
addData.open("proj1adds.data");
LinkedList<int> List;
Node<int> *head = NULL:
int add;
int i = 0;
while (!addData.eof()){
addData >> add;
List.add(i, add);
i++;
}
}
this is my add function
template < typename T >
void LinkedList < T >::add(int index, T element)
{
if (index == 0){
addFirst(element);
}
else if (index >= size){
addLast(element);
}
else
{
Node < T > * current = head;
for (int i = 1; i < index; i++)
current = current->next;
Node < T > * temp = current->next;
current->next = new Node < T > (element);
(current->next)->prev = current;
(current->next)->next = temp;
size++;
}
}
And these are my print functions
template<typename T>
void LinkedList<T>::printForward(Node<T> *head){
if(head==NULL){
return;
}
cout << head->element << endl;
printForward(head->next);
}
template<typename T>
void LinkedList<T>::printBackward(Node<T> *head){
if(head==NULL){
return;
}
printBackward(head->next);
cout << head->element << endl;
}
I think that I've loaded the data into the nodes, but I'm not sure if its ordered because I cant print it.
In a comment (but not in your question) you say that you're calling printFowards(head)
and printBackwards(head)
in main()
. But in main()
, the variable head
is a local variable that is set to NULL
. So the functions abort, and when you comment out the exit condition [ shudder ] you dereference a null pointer and get Undefined Behavior.
Maybe the list is being constructed correctly; it doesn't matter because your calls to the printing functions have no connection to the list.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.