码迷,mamicode.com
首页 > 其他好文 > 详细

21. 合并两个有序链表

时间:2018-08-15 22:58:31      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:tno   tco   test   ==   ring   有序链表   bsp   ble   turn   

21. 合并两个有序链表

https://leetcode-cn.com/problems/merge-two-sorted-lists/description/

package com.test;

public class Lesson021 {
    public static void main(String[] args) {

        ListNode l11 = new ListNode(1);
        ListNode l12 = new ListNode(2);
        ListNode l13 = new ListNode(4);
        l11.next = l12;
        l12.next = l13;
        printNode(l11);
        ListNode l21 = new ListNode(1);
        ListNode l22 = new ListNode(3);
        ListNode l23 = new ListNode(4);
        l21.next = l22;
        l22.next = l23;
        printNode(l21);
        ListNode res = mergeTwoLists(l11, l21);
        printNode(res); 
    }

     

    private static void printNode(ListNode l11) {
        System.out.print(l11.val);
        if(l11.next != null){
            System.out.print("->");
            printNode(l11.next);
        }else{
            System.out.println("");
        }
    }

    private static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null){
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        int val1 = l1.val;
        int val2 = l2.val;
        if (val1 > val2) {
            l2.next = mergeTwoLists(l1,l2.next);
            return l2;
        }else{
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        }

    }
}

 

21. 合并两个有序链表

标签:tno   tco   test   ==   ring   有序链表   bsp   ble   turn   

原文地址:https://www.cnblogs.com/stono/p/9484124.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!