为什么我不能使用 while 遍历 2 个双向链表?

Why can't I loop through 2 Doubly Linked Lists using while?

好的,任务是:

给定 2 个整数列表,按照以下规则将它们合并为一个:

  1. 交替添加两个列表中的所有偶数(list1 从第一个开始,list2 从最后一个开始)

  2. 将列表 1 中剩余的所有偶数相加。

  3. 从 list2 中添加所有剩余的偶数。

  4. 从第一个开始添加 list1 中的所有奇数

  5. 从最后一个开始添加 list2 中的所有奇数。

所以对于前。

列表 1: 1 2 3 4 4 5 6 列表 2:7 8 9 10

list3 应该是:10 2 8 4 4 6 1 3 5 9 7

但是我的函数returns 2 4 4 6 8 10 1 3 5 7 9

这是我写的函数:

public static void merge(DLL<Integer> list1 , DLL<Integer> list2, DLL<Integer> list3) {

    DLLNode<Integer> curr1=list1.getFirst();
    DLLNode<Integer> curr2=list2.getLast();

    while (curr1!=null && curr2!=null) {

        if (curr1.element%2==0) list3.insertLast(curr1.element);
        curr1=curr1.succ;

        if (curr2.element%2==0) list3.insertLast(curr2.element);
        curr2=curr2.pred;
    }

    if (curr1!=null) {
        while (curr1!=null) {
            if (curr1.element%2==0)
                list3.insertLast(curr1.element);
            curr1=curr1.succ;
        }
    }

    if (curr2!=null) {
        while (curr2!=null) {
            if (curr2.element%2==0)
                list3.insertLast(curr2.element);
            curr2=curr2.pred;
        }
    }

    curr1=list1.getFirst();
    while (curr1!=null) {
        if (curr1.element%2!=0)
            list3.insertLast(curr1.element);
        curr1=curr1.succ;
    }

    curr2=list2.getLast();
    while (curr2!=null) {
        if (curr2.element%2!=0)
            lista.insertLast(curr2.element);
        curr2=curr2.pred;
    }



}

不知何故,它没有进入第一个while循环。可能是什么原因造成的?

您没有添加偶数元素可互换。如果输出列表的第一个元素应该是第一个列表的偶数元素,则必须迭代第一个列表,直到在该列表中找到第一个偶数元素。然后你应该开始迭代第二个列表。

您可以使用一个标志来告诉您应该从哪个列表中获取下一个偶数元素:

boolean takeFirst = true;
while (curr1!=null && curr2!=null) {
    if (takeFirst) { // next even element should come from the first list
        if (curr1.element%2==0) {
            list3.insertLast(curr1.element);
            takeFirst = false;
        }
        curr1=curr1.succ;
    }
    if (!takeFirst) { // next even element should come from the second list
        if (curr2.element%2==0) {
            list3.insertLast(curr2.element);
            takeFirst = true;
        }
        curr2=curr2.pred;
    }
}