java - 交替合并两个链表,同时寻找最大值作为头

标签 java oop merge linked-list nodes

我正在开发一个链表程序,它允许我只循环列表一次,并且我无法将列表的元素复制到另一个数据结构。

假设列表不为空(至少有一个节点)并且最后一个节点的下一个节点为空。

下面的方法应该合并两个链表,合并后的链表的头应该是两个链表中的最大值。以下值在两个列表之间交替。

例如,如果我的输入是:

1 2 4 

3 5 6 7 8 9

我的输出是:

3 1 5 2 6 4 7 8 9

我弄清楚了如何分配头部,但我不知道如何正确合并列表的其余部分。

这是我的代码:

    public class LinkedListNode {
    private int value;
    private LinkedListNode next;

    public LinkedListNode(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public LinkedListNode getNext() {
        return next;
    }

    public void setNext(LinkedListNode next) {
        this.next = next;
    }
}

    public static LinkedListNode mergeLists (LinkedListNode head1, LinkedListNode head2){
        LinkedListNode firstList = head1;
        LinkedListNode secondList = head2;
        LinkedListNode tmp = new LinkedListNode(0);
        LinkedListNode result = head1;
        int checkWhichList=0;
        while(firstList!=null && secondList!=null){
            if (firstList.getValue()<=secondList.getValue()){
                result=secondList;
            }
            if (checkWhichList%2==0){
                tmp.setNext(head2.getNext());
                checkWhichList++;
            }
            else
                tmp.setNext(head1.getNext());
        }

        result.setNext(tmp);
        return result;
    }

最佳答案

一旦确定哪个节点具有最大值,您必须将两个头添加到结果(首先是最大值),然后移动firstListsecondList的指针

现在,您继续添加两个列表的结果,同时移动到每个列表的下一个节点,直到两个列表都不指向任何内容

示例:(以firstList为头的情况为例)

if(firstList.getValue() > secondList.getValue()) {
    //here firstList will be the head
    result = firstList;
    result.setNext(secondList);
    firstList = firstList.getNext();
    secondList = secondList.getNext();

    //Now alternating (adding firstList node before secondList)
    while(firstList != null || secondList != null) {
        if(firstList != null) {
            result.setNext(firstList);
            firstList = firstList.getNext();
        }        
        if(secondList != null) {
            result.setNext(secondList);
            secondList = secondList.getNext();
        }
    }
} else {
   //here secondList will be the head
   //continue with the code
}

关于java - 交替合并两个链表,同时寻找最大值作为头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30377986/

相关文章:

git - 从 development merge 到 master 时处理冲突

Git - 2个独立的开发分支 - 是否 cherry-pick ?

java - 不同项目中的应用程序上下文为空并且无法访问bean

java - 从方法传递变量以绘制一条线 - Java

通过对象调用Java接口(interface)方法

oop - 除了经典的基于类的方法之外,您能想象任何其他实现 OO 的方法吗?

java - 在 Servlet 中解析传入的多部分/表单数据参数的便捷方法

java - Travis-ci 无法构建其他 github 存储库贡献者所做的 github 提交

c# - Override Sealed 是有效的,但为什么在 C# 中不使用 Virtual Sealed?

visual-studio - 是否有一种明智的方法可以在分支之间合并 Visual Studio 项目文件 (.csproj)?