pigthatatepens
pigthatatepens

Reputation: 31

How do I add an element to the front of a linked list?

this is how the node is set up:

struct Node {
    Node *next;
    Node *prev;
    T datum;
};

this is my code

    //MODIFIES: this
    //EFFECTS:  inserts i into the front of the list
    void push_front(const T &datum)
    {
        Node newfirst = first; // set newnode to first
        &first = &datum;
        datum = newfirst;

    }



  Node *first;   // points to first Node in list, or 0 if list is empty
  Node *last;    // points to last Node in list, or 0 if list is empty

for some reason, I don't think this is right.

Upvotes: 1

Views: 208

Answers (2)

davidhigh
davidhigh

Reputation: 15468

You want to (i) create a new node with a valid content, and (ii) set is as the first node of your list. You can do that like in the following example:

void push_front(const T &datum)
{
    Node* newFirst = new Node;  //construct new Node
    newFirst->next = first;     // set newFirst's next node
    newFirst->datum = datum;   //set the content
    first = newFirst;          //assign new first node;
}

This is just as a sketch; for more details, you should post more code (such as mentioned in one of the comments).

Another thing to mention: I would prefer using a unique_ptr for one of those Node pointers, e.g.

struct Node {
    std::unique_ptr<Node> next;
    Node *prev;
    T datum;
};

This you can very easily destroy the list (and also avoid the new command which is often recommended in modern C++).

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

It seems you need the following

//this is my code
    //MODIFIES: this
    //EFFECTS:  inserts i into the front of the list
void push_front(const T &datum)
{
    first = new Node { first, nullptr, datum };

    if ( !last ) last = first;
}

If your compiler does not support initializer lists for the operator new then you can write

//this is my code
    //MODIFIES: this
    //EFFECTS:  inserts i into the front of the list
void push_front(const T &datum)
{
    Node *tmp = new Node();

    tmp->datum = datum;
    tmp->next = first;

    first = tmp;

    if ( !last ) last = first;
}

Upvotes: 1

Related Questions