Tom Lilletveit
Tom Lilletveit

Reputation: 2002

C++: linked list head and tail pointers

I don´t get this, when I call head->valueit returns me the last value added to the linked list. Should it not return me the first item since head is only set when it is empty? correct? I am thinking maybe there is there some other bug in the code.

void LinkedListPQueue::enqueue(const string& elem) {
    cell *newCell = new cell;
    newCell->value = elem;
    newCell->next = NULL;
    if(this->isEmpty()) {
        this->head = this->tail = newCell;
    } else {
        // find smallest and put it there

        this->tail->next = newCell;
        this->tail = newCell;
    }
}

declared in header

struct cell {
    std::string value;
    cell *next;
};
cell *head, *tail;

Upvotes: 1

Views: 5152

Answers (1)

hmatar
hmatar

Reputation: 2419

My be isEmpty is not implemented correctly so everytime you add a new node you re-assign the head to that node

Upvotes: 6

Related Questions