码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-08-29 11:11:08      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:content   his   链表   sys   null   www   ||   print   pid   

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
 
 
 
题目链接:
 
 
package com.sunshine.OFFER66_SECOND;

public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

 

 
package com.sunshine.OFFER66_SECOND;

import org.junit.Test;

public class A16_Merge {

    @Test
    public void test() {
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(3);
        ListNode n3 = new ListNode(5);
        ListNode m1 = new ListNode(2);
        ListNode m2 = new ListNode(4);
        ListNode m3 = new ListNode(6);
        n1.next = n2;
        n2.next = n3;
        m1.next = m2;
        m2.next = m3;
        ListNode merge = Merge(n1, m1);
        while (null != merge) {
            System.out.println(merge.val);
            merge = merge.next;
        }
    }


    public ListNode Merge(ListNode list1, ListNode list2) {
        ListNode ans = null;
        ListNode cur = null;
        while (list1 != null || list2 != null) {
            while (list1 != null && (list2 == null || list1.val <= list2.val)) {
                if (null != cur) {
                    cur.next = list1;
                    cur = cur.next;
                } else {
                    cur = list1;
                    ans = list1;
                }
                list1 = list1.next;
            }
            while (list2 != null && (list1 == null || list1.val >= list2.val)) {
                if (null != cur) {
                    cur.next = list2;
                    cur = cur.next;
                } else {
                    cur = list2;
                    ans = list2;
                }
                list2 = list2.next;
            }
        }
        return ans;
    }
}

 

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

标签:content   his   链表   sys   null   www   ||   print   pid   

原文地址:https://www.cnblogs.com/MoonBeautiful/p/11428488.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!