简体   繁体   中英

Printing head and tail of singly 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?

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 

There are actually two options:

  1. Keep track of the tail : This may sound stupid, but just add a private Node* to your class which keeps track of the last element in the list. Don't forget to update this pointer if necessary!
  2. Move through your list : You know the head node points to the next node. In turn, that node will point to its subsequent node. You see the pattern? You could do this, until you hit a node which does not point to a next node. This is your last node!

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM