合并两个有序的单链表,合并后的链表依然有序(java)

话不多说,直接上代码

public class SignleLinkList {
    public static void main(String[] args) {
        Node node1 = new Node(2);
        Node node3 = new Node(3);
        node1.next = node3;


        Node node2 = new Node(1);
        Node node4 = new Node(4);
        Node node5 = new Node(5);

        node2.next = node4;
        node4.next = node5;

        System.out.println("单链表1");
        print(node1);
        System.out.println("单链表2");
        print(node2);
        System.out.println("合并后的单链表");
        print(merge(node1,node2));

    }

    /**
     * 合并有序单链表
     * @param node1
     * @param node2
     * @return
     */
    public static Node merge(Node node1,Node node2){
        Node cur1 = node1;
        Node cur2 = node2;
        Node temp = new Node(0);
        Node cur = temp;
        while (true){
            if(cur1 == null){
                cur.next = cur2;
                break;
            }
            if(cur2 == null){
                cur.next = cur1;
                break;
            }
            if(cur1.data<cur2.data){
                cur.next = cur1;
                cur = cur1;
                cur1 = cur1.next;
            }else{
                cur.next = cur2;
                cur = cur2;
                cur2 = cur2.next;
            }
        }
        return temp.next;
    }

    /**
     * 打印链表
     * @param head
     */
    public static void print(Node head){
        Node temp = head;
        while (temp != null){
            System.out.println(temp);
            temp = temp.next;
        }
    }

    static class Node{
        public int data;
        public Node next;

        public Node(int data) {
            this.data = data;
        }

        @Override
        public String toString() {
            return "Node{" +
                    "data=" + data +
                    '}';
        }
    }
}

测试结果打印如下:
测试结果

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值