剑指offer之合并两个排序的链表

题目:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路:归并排序的思想

public class ListNodeMerge {

    public ListNode merge(ListNode list1,ListNode list2){
        if(list1==null && list2!=null)
            return list2;
        if(list2==null && list1!=null)
            return list1;
        if(list1==null || list2==null)
            return null;
        ListNode p1 = list1;
        ListNode p2 = list2;
        ListNode p = null;
        if(list1.val>list2.val)
        {
            p = list2;
            p2 = p2.next;
        }
        else
        {
            p=list1;
            p1 = p1.next;
        }
        //System.out.println(p.val);
        while(p1!=null && p2!=null){
            if(p1.val>p2.val){
                p.next= p2;
                p=p2;
            //  System.out.println(p.val);
                p2=p2.next; 
            }
            else{
                p.next= p1;
                p=p1;
            //  System.out.println(p.val);
                p1=p1.next; 
            }       
        }
        if(p1==null)
            p.next=p2;
        else
            p.next=p1;
        if(list1.val>list2.val)
        {
            return list2;
        }
        else
        {
            return list1;
        }

    }
    public static void main(String[] args) {
        ListNode head = new ListNode(0);
        ListNode a = new ListNode(2);
        ListNode b = new ListNode(4);
        ListNode c = new ListNode(6);
        ListNode d = new ListNode(8);
        head.next= a;
        a.next=b;
        b.next=c;
        c.next=d;   
        ListNode head1 = new ListNode(1);
        ListNode e = new ListNode(3);
        ListNode f = new ListNode(5);
        ListNode g = new ListNode(7);
        ListNode h = new ListNode(9);
        head1.next= e;
        e.next=f;
        f.next=g;
        g.next=h;

        ListNodeMerge l = new ListNodeMerge();
        ListNode node = l.merge(head, head1);
        while(node!=null){
            System.out.print(node.val+",");
            node=node.next;
        }

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值