Java 合并两个链表,得到一个新的链表

如题:

合并两个链表,得到一个新的链表 a = 1->2->3->4 和 b = 2->3->5 合并为 c = 1->2->3->4->5,另外只能返回结果c,不能修改a,b两个链表的数据。

链表元素定义

/**
 * 链表元素定义
 * Create by zxb on 2017/8/27
 */
public class Element<T> {

    private Element<T> next;

    private T value;

    public Element<T> getNext() {
        return next;
    }

    public void setNext(Element<T> next) {
        this.next = next;
    }

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }
}
列表模板接口
/**
 * 列表模板接口
 * Created by zhengxb on 2017/8/27.
 */
public interface IList<T> {

    boolean pushBack(T newElement);

    boolean popFront();

    Element<T> front();

    int size();

    void display();
}
链表实现
/**
 * 链表实现
 * Create by zxb on 2017/8/27
 */
public class ListImpl<T> implements IList<T> {

    private Element<T> first = null;

    private Element<T> last = null;

    private int size = 0;

    @Override
    public boolean pushBack(T newElement) {
        Element<T> element = new Element<>();
        element.setValue(newElement);
        if (size == 0) {
            first = element;
            size++;
            return true;
        }
        if (last == null) {
            last = new Element<>();
            last.setValue(newElement);
            first.setNext(last);
        } else {
            last.setNext(element);
            last = element;
        }
        size++;
        return true;
    }

    @Override
    public boolean popFront() {
        if (size == 0) {
            return false;
        }
        first = first.getNext();
        size--;
        if (size == 0) {
            last = null;
        }
        return true;
    }

    @Override
    public Element<T> front() {
        return first;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public void display() {
        if (first == null) {
            return;
        }
        Element<T> temp = first;
        System.out.print("list={");
        do {
            System.out.print(temp.getValue());
            temp = temp.getNext();
            if (temp != null) {
                System.out.print(", ");
            }
        } while (temp != null);
        System.out.println("}");
    }
}

CombineUtil函数

/**
 * 合并两个链表,得到一个新的链表
 * a = 1->2->3->4 和 b = 2->3->5 合并为 c = 1->2->3->4->5
 * 另外只能返回结果c,不能修改a,b两个链表的数据。
 * Create by zxb on 2017/9/10
 */
public class CombineUtil {

    public static <T extends Number> IList<T> combine(IList<T> list1, IList<T> list2) throws Exception {
        if (list1 == null || list1.size() == 0 || list2 == null || list2.size() == 0) {
            throw new Exception("参数错误");
        }
        Element<T> currentPosition1 = list1.front();
        Element<T> currentPosition2 = list2.front();
        //定义最终链表
        IList<T> list = new ListImpl<>();
        //定义最终链表当前末尾元素
        T currentValue = null;
        //定义当前处理的链表序号
        int currentListIndex = currentPosition1.getValue().longValue() <= currentPosition2.getValue().longValue() ? 1 : 2;
        while (currentPosition1 != null || currentPosition2 != null) {
            if (currentPosition1 == null) {
                currentListIndex = 2;
            }
            if (currentPosition2 == null) {
                currentListIndex = 1;
            }
            if (currentListIndex == 1) {
                if (currentPosition2 == null || currentPosition1.getValue().longValue() <= currentPosition2.getValue().longValue()) {
                    //跳过相同元素
                    if (currentValue == null || (currentValue != null && currentValue.longValue() != currentPosition1.getValue().longValue())) {
                        currentValue = currentPosition1.getValue();
                        list.pushBack(currentValue);
                    }
                    currentPosition1 = currentPosition1.getNext();
                    //如果下一个元素相同,则另一个链表的当前指针后移
                    if (currentPosition1 != null && currentPosition2 != null && currentPosition1.getValue().longValue() == currentPosition2.getValue().longValue()) {
                        currentPosition2 = currentPosition2.getNext();
                    }
                } else {
                    currentListIndex = 2;
                }
            } else {
                if (currentPosition1 == null || currentPosition2.getValue().longValue() <= currentPosition1.getValue().longValue()) {
                    //跳过相同元素
                    if (currentValue == null || (currentValue != null && currentValue.longValue() != currentPosition2.getValue().longValue())) {
                        currentValue = currentPosition2.getValue();
                        list.pushBack(currentValue);
                    }
                    currentPosition2 = currentPosition2.getNext();
                    //如果下一个元素相同,则另一个链表的当前指针后移
                    if (currentPosition1 != null && currentPosition2 != null && currentPosition1.getValue().longValue() == currentPosition2.getValue().longValue()) {
                        currentPosition1 = currentPosition1.getNext();
                    }
                } else {
                    currentListIndex = 1;
                }
            }
        }
        return list;
    }

    public static void main(String[] args) throws Exception {
        IList<Integer> list1 = new ListImpl<>();
        list1.pushBack(1);
        list1.pushBack(2);
        list1.pushBack(3);
        list1.pushBack(4);
        IList<Integer> list2 = new ListImpl<>();
        list2.pushBack(2);
        list2.pushBack(3);
        list2.pushBack(5);
        IList<Integer> list3 = CombineUtil.combine(list1, list2);
        list3.display();
    }
}
运行结果:


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JAVA可以通过以下步骤将两个有序链表合并一个有序链表: 1. 创建一个链表头节点`newNode`和指针`tmp`,用来构建合并后的有序链表。 2. 设置两个链表的头结点分别为`head1`和`head2`。 3. 比较`head1`和`head2`节点的值,将较小的节点连接到`tmp`节点的后面,然后将指针`tmp`指向加入的节点。 4. 移动被选中的节点所在的链表的头指针,即将`head1`或`head2`指向下一个节点。 5. 重复步骤3和步骤4,直到其中一个链表走完。 6. 当其中一个链表走完后,将另一个链表剩下的节点直接连接到`tmp`节点的后面,使其`tmp.next = head1/head2`。 7. 返回链表头节点`newNode.next`即为合并后的有序链表。 通过以上步骤,JAVA可以将两个有序链表合并一个有序链表。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [合并两个有序链表java)](https://blog.csdn.net/intmainreturn/article/details/128490890)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [合并两个有序链表Java)](https://blog.csdn.net/m0_63036262/article/details/124417509)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值