21. 合并两个有序链表
Posted stono
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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; } } }
以上是关于21. 合并两个有序链表的主要内容,如果未能解决你的问题,请参考以下文章