Reputation: 51
So I have a singly linked list below that prints out a list of Movie objects in alphabetical order based by the director name. I'm trying to print the first element (the head) and the last element (the tail) in the list but I'm struggling to figure out how. I attempted to print out the head below but it just prints the memory address for some reason instead of the actual object value.
As for the tail, I'm not quite sure how I would access the last element in the list and was wondering if someone could offer guidance or push me in the right direction?
EDIT: Actually I realized I should call head->data->print() just like I did with current node to print the head. I just need to figure out how to maintain a head AND tail in my list rather than only a head.
List.cc
void List::print() const{
Node* current = head;
while (current != NULL) {
current->data->print();
current = current->next;
}
cout << "HEAD: \n" << head->data->print() << endl; //prints memory address?
// cout << "TAIL: \n" << head << endl;
}
List.h
#ifndef LIST_H
#define LIST_H
#include "Movie.h"
class List{
class Node{
public:
Movie* data;
Node* next;
};
public:
List();
~List();
void add(Movie*);
void print() const;
private:
Node* head;
};
#endif
Upvotes: 0
Views: 1300
Reputation: 657
There are actually two options:
Point 1 would be advantageous in case you have a really long list. If you would use point 2 in this case, you actually have to traverse the complete list. However, no matter which option you choose, I would advise you to start with implementing option 2. I think this option will give you some nice insight.
Upvotes: 1