Linked list insertion

83 Views Asked by At

The EmissonList object is a List of Shows with certain info. The problem I look for is in the insert function.

class EmissionList {
private:
Emission *head=NULL;
public:
void insert(Emission *aNode);
Emission *getHead() {
    return head;
};
void putHead(Emission *newHead) {
    head=newHead;
    head->next = NULL;
}
void printEmissions();
};


void EmissionList::insert(Emission *aNode) {
Emission *ptr=getHead();
if (head == NULL){
    putHead(aNode);
}else{
    while(ptr!= NULL){
        ptr = ptr->next;
    }
    ptr = aNode;
    ptr->next=NULL;
}}

I am trying to add to the list but I encounter problems.

2

There are 2 best solutions below

1
On

In your code when you set ptr = aNode ptr is not the 'next' of last element and so original list is unchanged

I suggest you std::list or, at least

for (Emission **iter = &head ; *iter != NULL ; )
    iter = &((*iter)->next) ;
*iter = aNode ;

It's the simplest insertion (at end) I have found so far.

1
On

First of all the design of the class EmissionList is bad.

Nevertheless the function can be defined the following way

void EmissionList::insert( Emission *aNode ) 
{
    Emission *current = getHead();

    if ( current == NULL )
    {
        putHead( aNode );
    }
    else
    {
       while ( current->next ) current = current->next;
       aNode->next = current->next;
       current->next = aNode;
    }
}