Am I adding the item to the linked list correctly

advertisements

In this case, I need to implement addFront() method which is to keep adding a integer in front of a linked-list.

    class Node{
    public:
    int data;
    Node* next;
    Node* prev;
    }
    class List {

    void addFront(int item);

    protected:
    Node* dummyNode;
    int numItems; //number of item is the linkedlist
};

Below is what I tend to implement addFront():

  void addFront(int data){
    Node* head = new Node();

    if(numItems == 0) //if no item in the list.
    {
      //Set the head node to be dummyNode
      head = dummyNode;

      //Because the next node the head is pointing to is NULL.
      head -> next = NULL;
    }

    //Create a new node.
    Node* newNode = new Node();

    //Set value
    newNode->data = data;

    //Let the previous pointer of dummyNode points to newNode.
    head->prev = newNode;

    //Re-set head to be newNode.
    head = newNode;

    numItems++;
}

Am I doing correctly? If not, why? If yes, is there any better way to do this?


I won't go into too many details as this appears to be a homework assignment, but the short answer is, no.

Node* head = new Node();
if(numItems == 0) //if no item in the list.
{
    //Set the head node to be dummyNode
    head = dummyNode;
    //...
}

You have a memory leak in the code above.