LeetCode--021--合并两个有序链表(java)

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

哎,这java语法忘完了,也能糊弄通过,老天真要我搞大数据开发吗???????AI我还能刚多久。。。。。。。。。。

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
11         ListNode l3 = new ListNode(-1);
12         ListNode dummy = l3;
13         while(l1!=null && l2 != null){
14             if(l1.val < l2.val){
15                 dummy.next = l1;
16                 dummy = l1;
17                 l1 = l1.next;
18             }else{
19                 dummy.next = l2;
20                 dummy = l2;
21                 l2 = l2.next;
22             }
23         }
24         if(l1 == null){
25             l1 = l2;
26         }
27         dummy.next = l1;
28         return l3.next;
29     }
30 }

官方的递归:

 1 class Solution {
 2     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
 3         if(l1 == null) return l2;
 4         if(l2 == null) return l1;
 5         if(l1.val < l2.val){
 6             l1.next = mergeTwoLists(l1.next,l2);
 7             return l1;
 8         }else{
 9             l2.next = mergeTwoLists(l1,l2.next);
10             return l2;
11         }
12     }
13 }

2019-04-18 20:54:58

posted @ 2019-04-18 20:55  Assange  阅读(782)  评论(0编辑  收藏  举报