C++ - printing head and tail of linked list

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?

List.cc
1
2
3
4
5
6
7
8
9
10
	void List::print() const{
	  Node* current = head;

	  while (current != NULL) {
		current->data->print();
		current = current->next;
	  }
	  cout << "HEAD: \n" << head << endl; //prints memory address?
	 // cout << "TAIL: \n" << head << endl;
	}


List.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
	#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 
Last edited on
 
 cout << "HEAD: \n" << head << endl; //prints memory address? 


Why not as you used previously:

 
head->data->print();



For the tail, you need something like (not tried):

1
2
3
4
5
6
7
Node* previous {nulltr};

for (Node *current = head; current != nullptr; current = current->next)
	previous = current;

if (previous != nullptr)
    previous->data->print();


Another alternative is to maintain a tail pointer as well as a head pointer.
Last edited on
Topic archived. No new replies allowed.