Невозможно распечатать элементы в связанном списке после объединения двух массивов в один список - PullRequest
1 голос
/ 02 февраля 2020

Я работаю над заданием для DS и Al go Мне даны два отсортированных целочисленных списка или массива, затем я должен объединить их в один список. Я решил использовать две очереди для каждого массива, поместив каждый элемент в очередь, затем выполнить некоторые сравнения и поместить их в односвязный список. Теперь проблема, с которой я столкнулся, заключается в том, что в первом массиве снова и снова печатается только первый элемент. Моя цель - убрать элементы из очереди и поместить их в связанный список от наименьшего к наибольшему. Также счет в while l oop используется для остановки l oop, если он равен длине обоих массивов - 1.

MergeQueue. java

    int[] A = {1, 3, 5, 7, 9}; // our first array A
    int[] B = {2, 3, 6, 8, 10}; // our second array B
    int length = A.length + B.length - 1; // get the length of both A and B
    //System.out.println(length);
    int count = 0; // this is a counter used to check that once count is equal to the length(A+B) then we break the loop
    int frontA, dequeueA;
    int frontB, dequeueB;

    // we can use a singly linked list to store elements of A and B
    SingleLinkedList S = new SingleLinkedList();
    QueueLinkList queueA = new QueueLinkList(); // our queue for A type integer
    QueueLinkList queueB = new QueueLinkList(); // our queue for B type integer

    // Add elements from A to the queue
    for(int i = 0; i < A.length; i++) {
        // so add element from A to the queue
        queueA.enqueue(A[i]);
    }

    // Add elements from B to the queue
    for(int i = 0; i < B.length; i++) {
        // so add element from B to the queue
        queueB.enqueue(B[i]);
    }
    // now begins the conditions
    while(count != length) {
        // only return the element in the front not remove it
        frontA = queueA.front(); 
        frontB = queueB.front(); 

        if(frontA < frontB) {
            dequeueA = queueA.dequeue(); // remove the element and add it to the linked list
            // add dequeueA to list S
            S.add(dequeueA); // add the element to the singly linked list
            count++; // increment the counter
        }
        else if(frontB < frontA) {
            dequeueB = queueB.dequeue();
            // add dequeueB to list S
            S.add(dequeueB); // add the element to the singly linked list
            count++; // increment the counter
        }
        // if the elements are the same then remove from queue and add anyone.
        else if(frontA == frontB || frontB == frontA) {
            dequeueA = queueA.dequeue();
            dequeueB = queueB.dequeue();
            // add either dequeueA or B
            S.add(dequeueA); // add the element to the singly linked list
            count++; // increment the counter
        }
        // if queue A is empty and queue B is not then add remaining elements from B to S.
        else if(queueA.isEmpty() && !queueB.isEmpty()){
            // add remaining elements from B to the list
            dequeueA = queueA.dequeue(); 
            S.add(dequeueA);
            count++; // increment the counter
        }
        // if queue B is empty and queue A is not then add remaining elements from B to S.
        else if(queueB.isEmpty() && !queueA.isEmpty()) {
            // add remaining elements from B to the list
            dequeueB = queueB.dequeue();
            S.add(dequeueB);
            count++;
        }
    }
    System.out.println("Our set S:");
    S.print(); // call the print method which displays every element in the singly linked list

1 Ответ

0 голосов
/ 14 февраля 2020

В этой части кода

else if(frontA == frontB || frontB == frontA) {
            dequeueA = queueA.dequeue();
            dequeueB = queueB.dequeue();
            // add either dequeueA or B
            S.add(dequeueA); // add the element to the singly linked list
            count++; // increment the counter
}

Вам необходимо увеличить счетчик в 2 раза, так как, даже если вы добавляете в список ссылок, как только вы удаляете один и тот же элемент из обеих очередей и, следовательно, два элемента получают удален

...