合并2个有序链表

两种方法实现:

1.递归

2.非递归

public class MergeList {
    public static void main(String[] args){
        Node p1=new Node(2);
        Node p2=new Node(3);
        Node p3=new Node(5);
        Node p4=new Node(9);
        p1.next=p2;
        p2.next=p3;
        p3.next=p4;
        Node q1=new Node(2);
        Node q2=new Node(4);
        Node q3=new Node(6);
        Node q4=new Node(7);
        Node q5=new Node(8);
        q1.next=q2;
        q2.next=q3;
        q3.next=q4;
        q4.next=q5;
        //Node n=new MergeList().merge(p1,q1);
        Node n=new MergeList().merge2(p1,q1);
        while(n!=null){
            System.out.print(n.data+" ");
            n=n.next;
        }


    }
    public Node merge(Node h1,Node h2){
        //首先,判断是否有链表为空
        if(h1==null)
            return h2;
        if(h2==null)
            return h1;
        Node h0=null;

        //比较
        if(h1.data<h2.data) {
            h0 = h1;
            h0.next = merge(h1.next, h2);
        }else{
            h0=h2;
            h0.next = merge(h1,h2.next);
        }
        return h0;

    }
    public Node merge2(Node h1,Node h2) {
        if (h1 == null) {
            return h2;
        }
        if (h2 == null) {
            return h1;
        }
        //确定头指针
        Node tailNode = null;//指向新链表最后一个结点
        Node head = null;//指向合并后链表第一个结点
        if (h1.data <= h2.data) {
            head = h1;
            h1 = h1.next;//指向第二个结点
        } else {
            head = h2;
            h2 = h2.next;
        }
        tailNode = head;//指向第一个结点

        while (h1 != null && h2 != null) {
            if (h1.data <= h2.data) {
                tailNode.next = h1;
                h1 = h1.next;
            } else {
                tailNode.next = h2;
                h2 = h2.next;
            }
            tailNode = tailNode.next;//后移
        }

        //剩余结点的处理
        if (h1==null) {
            tailNode.next = h2; 
        } else if (h2==null) {
            tailNode.next = h1; 
        }
        return head; 
    }


}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值