1

So I have the following class:

template <class T>
class List : public ContainerIfc <T> {
public:
    List();
    ~ List();
    List(const List&);
    List <T>& operator = (List&);
    List <T>& pushFront(T);
    List <T>& pushBack(T);
    List <T>& popFront(T&);
    List <T>& popBack(T&);
    int getSize();
    bool isEmpty();
    T front();
    T back();
    T& operator [](int);
private:
    Node<T> *head;
};

and the following node:

template <class T>
class Node {
public:
    T data;
    Node<T> *next;
    Node(T e) {
        data = e;
        next = NULL;
    }
};

I want to write a pushFront function that adds a value to the front of the linked list. I already have the following code. What I can't figure out is how to get it to return a List object. I think that my function would work as it is, it just wouldn't return a List. Any ideas as to how one might go about doing that?

template <class T>
List <T>& List<T>::pushFront(T n){

    Node<T> *temp = new Node<T>(n);
    temp->next = head;



}
Sarah Sepanski
  • 189
  • 2
  • 10

1 Answers1

6

A few issues here. Firstly, you never update head to point to the new node you added.

Secondly, as far as returning a List object reference--you have the implicit parameter, this that is a pointer to the object you're currently modifying. Simply return its dereference:

template <class T>
List <T>& List<T>::pushFront(T n){

    Node<T> *temp = new Node<T>(n); //Create a new node
    temp->next = head; //point its next to the current head
    head = temp; //Update head so our node is front of the list

    return *this; //Return a reference of ourself
}

Lastly, in your Node constructor, beware of NULL (see here for more information).

Also, as a quick aside--the way you're implementing your linked list you should be careful of the member functions back(), push_back() and pop_back(). Given that you only have a head pointer, each of these operations will require you to loop through the whole list (this is referred to as O(n) runtime). This might not be a problem on small lists, but as your lists get larger, this will become worse and worse.

You'll notice that in widely used libraries like the C++ Standard Library, functions that would be that inneficient are often simply not even implemented (see vector, notice the missing push/pop_front). You could fix this by adding a tail pointer and changing to a doubly linked list, but of course that would make all of your other functions more complicated. At the end of the day, it's a tradeoff.

scohe001
  • 15,110
  • 2
  • 31
  • 51