java结合两个链表 [英] java combine two linkedlist

查看:71
本文介绍了java结合两个链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对合并两个链表有疑问。基本上,我想将一个链表添加到另一个链表上。

I have a question for combining two linkedlist. Basically, I want to append one linkedlist to the other linkedlist.

这是我的解决方案。有没有更有效的方法可以做到而无需循环第一个链表?

Here is my solution. Is there a more efficient way to do it without looping the first linkedlist? Any suggestion would be appreciated.

    static Node connect(LinkedList list1, LinkedList list2) {
    Node original = list1.first;
    Node previous = null;
    Node current = list1.first;
    while (current != null) {
        previous = current;
        current = current.next;
    }
    previous.next = list2.first;
    return original;
}


推荐答案

使用 list1.addAll(list2)将list2追加到list1的末尾。

Use list1.addAll(list2) to append list2 at the end of list1.

这篇关于java结合两个链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆