Java实现合并两个有序单链表,合并后依旧有序。

本文详细介绍了如何使用Java编程语言,通过高效算法将两个已排序的单链表合并,确保合并后的链表仍然有序。内容涵盖算法设计、代码实现及复杂度分析。
摘要由CSDN通过智能技术生成
package com.yyh;

/**
 * @author yyh
 * @create 2021-04-11 17:38
 */
public class SLinkList {
   
    public static void main(String[] args) {
   
        SingleLinkedList s1 = new SingleLinkedList();
        SingleLinkedList s2 = new SingleLinkedList();
        HeroNode node1 = new HeroNode(1, "lixing1");
        HeroNode node2 = new HeroNode(2, "lixing2");
        HeroNode node3 = new HeroNode(3, "lixing3");
        s1.add(node1);
        s1.add(node3);
        s1.add(node2)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现两个有序单链表合并,可以按照以下步骤进行: 1. 创建一个新的链表头节点,并用一个变量newHead指向它。 2. 创建两个当前节点变量,分别指向两个有序链表的头节点,命名为list1和list2。 3. 使用一个循环遍历两个有序链表,直到其中一个链表为空。 4. 在循环内部,比较list1和list2当前节点的值大小。 - 如果list1的值小于等于list2的值,将list1的节点连接到新链表中,并将list1指针后移。 - 如果list2的值小于list1的值,将list2的节点连接到新链表中,并将list2指针后移。 5. 循环结束后,将剩余未遍历完的链表连接到新链表的末尾。 6. 返回新链表的头节点newHead。 以下是Java代码示例: ```java class Node { int value; Node next; public Node(int value) { this.value = value; } } public class Main { public static Node mergeLinkedLists(Node list1, Node list2) { if (list1 == null) { return list2; } if (list2 == null) { return list1; } Node newHead; if (list1.value <= list2.value) { newHead = list1; list1 = list1.next; } else { newHead = list2; list2 = list2.next; } Node current = newHead; while (list1 != null && list2 != null) { if (list1.value <= list2.value) { current.next = list1; list1 = list1.next; } else { current.next = list2; list2 = list2.next; } current = current.next; } if (list1 != null) { current.next = list1; } if (list2 != null) { current.next = list2; } return newHead; } public static void main(String[] args) { // 创建第一个有序链表 Node list1 = new Node(1); list1.next = new Node(3); list1.next.next = new Node(5); // 创建第二个有序链表 Node list2 = new Node(2); list2.next = new Node(4); list2.next.next = new Node(6); // 合并链表 Node mergedList = mergeLinkedLists(list1, list2); // 打印合并链表的值 Node current = mergedList; while (current != null) { System.out.print(current.value + " "); current = current.next; } } } ``` 运行上述代码,将输出合并链表的值:1 2 3 4 5 6。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值