mardi 18 septembre 2018

Error in merging two sorted lists using no parameters

struct Node
{
    T data;
    Node *next;
};
Node *front;
Node *back;

List() {
    front = nullptr;
    back = nullptr;
}

I have the following function that does the merging of two sorted lists. But the function is not working. I don't understand where the mistake was. Can anyone please explain this.

void merge_with(List<T> &other)
{
    Node* a = front;
    Node* b = other;
    Node *aCurrent = a->front;
    Node *temp;
    //a empty
    if (b->front == NULL) {
        return;
    }
    //a empty, b not empty
    if (a->front == NULL && b->front != NULL) {
        if (b->front->next == NULL) {
            a->front = b->front;
            a->back = b->back;
            b->front = NULL;
            b->back = NULL;

            return;
        }
    }


    else {
        while (b->front != NULL) {
            //in front
            if (b->front->val < aCurrent->val) {
                //printf("\nfound front: %d\n", b->front->val);
                temp = b->front;
                b->front = b->front->next;

                temp->next = a->front;
                a->front = temp;

                //(a->count)++;
                continue;
            }

            //in between
            if (b->front->val >= aCurrent->val && b->front->val < aCurrent->next->val) {
                //printf("\nfound between: %d\n", b->front->val);
                temp = b->front;
                b->front = b->front->next;

                temp->next = aCurrent->next;
                aCurrent->next = temp;

                aCurrent = aCurrent->next;

                (a->count)++;
                continue;
            }
            //traverse
            aCurrent = aCurrent->next;
            if (aCurrent->val == a->back->val) {

                break;
            }
        }

        //in back
        aCurrent = a->back;
        while (b->front != NULL) {

            temp = b->front;
            b->front = b->front->next;

            temp->next = aCurrent->next;
            aCurrent->next = temp;

            aCurrent = aCurrent->next;

            //b->front = b->front->next;
            //(a->count)++;
        }

    }

    b->front = NULL;
    b->back = NULL;
    return;
}

I have the following function that does the merging of two sorted lists. But the function is not working. I don't understand where the mistake was. Can anyone please explain this.

Aucun commentaire:

Enregistrer un commentaire