zoukankan      html  css  js  c++  java
  • 21. 合并两个有序链表

    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;
            }
    
        }
    }

     参考参考:

    参考参考:

  • 相关阅读:
    几种任务调度的 Java 实现方法与比较
    nginx配置
    生产消费_lock和阻塞队列
    阻塞队列
    countdownlatch+cyclicbarrier+semphore
    01背包
    skiplist
    lru
    按序打印_lock和condition
    按序打印_volatile 无法保证顺序
  • 原文地址:https://www.cnblogs.com/stono/p/9484124.html
Copyright © 2011-2022 走看看