通过从Java中获取两个元素来合并两个单链表

时间:2015-07-10 11:08:41

标签: java list

我需要输出SLL(单链表),这是以这种方式合并两个人的结果:

List1 = 5 6 7

List2 = 1 2 3 4

OutputList = 5 6 1 2 7 3 4

List1 = 5 6 0 2 3 3

List2 = 2 4 5 2

OutputList = 5 6 2 4 0 2 5 2 3 3

我在获取节点的成功者时得到NullPointerException,或者我陷入了while循环。你能帮我吗?

这是我到目前为止所做的:

public SLL < E > specialJoin(SLL < E > list1, SLL < E > list2) {
    SLL result = new SLL();
    SLLNode temp1 = list1.first;
    SLLNode temp2 = list2.first;

    while (temp1 != null && temp2 != null) { // if there are still nodes in the lists
        result.insertLast(temp1.element); // first insert the first element
        if (temp1.succ != null) { // then check if there is still something
            result.insertLast(temp1.succ.element); // and add the second element
            temp1 = temp1.succ.succ; // at the end the next node will be the node after the succ of  the temporary element
        }

        rezultat.insertLast(temp2.element); // the same for the seconod list
        if (temp2.succ != null) {
            result.insertLast(temp2.succ.element);
            temp2 = temp2.succ.succ;
        }
    }
    // if there are still nodes in on of the lists we are apending them
    while (temp1 != null) {
        result.insertLast(temp1.element);
        temp1 = temp1.succ;
    }
    while (temp2 != null) {
        result.insertLast(temp2.element);
        temp2 = temp2.succ;
    }
    return result;
}

1 个答案:

答案 0 :(得分:0)

在第一个while循环中,当你到达任一列表的末尾时,你会遗漏一件事:

    while(temp1 != null && temp2 != null){ // if there are still nodes in the lists
        result.insertLast(temp1.element); // first insert the first element
        if(temp1.succ != null){ // then check if there is still something
            result.insertLast(temp1.succ.element); // and add the second element
            temp1= temp1.succ.succ; // at the end the next node will be the node after the succ of  the temporary element
        } else { // added
            temp1= temp1.succ; // which is the same as temp1=null;
        }

        rezultat.insertLast(temp2.element); // the same for the seconod list
        if(temp2.succ != null){
            result.insertLast(temp2.succ.element);
            temp2 = temp2.succ.succ;
        } else { // added
            temp2 = temp2.succ; // which is the same as temp2=null;
        }
    }

当其中一个列表中只剩下一个节点时,那些添加的else子句会处理这种情况。没有它们,你可能陷入无限循环。