## LeetCode 第21题 合并两个有序链表

`/*将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。示例：输入：1->2->4, 1->3->4输出：1->1->2->3->4->4Definition for singly-linked list. public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } */`
``` 1 class Solution21 {
2
3
4   /*
5     思路:迭代  时间O(n)
6  */
7   public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
8     if (l1 == null) {
9       return l2;
10     }
11     if (l2 == null) {
12       return l1;
13     }
14
15     ListNode newList = new ListNode(0);//headNode
16     ListNode nodePos = newList;
17
18     while (l1 != null && l2 != null) {
19       /*
20       将list1中结点放入newList
21        */
22       if (l1.val <= l2.val) {
23         nodePos.next = l1;
24         l1 = l1.next;
25       } else {
26         /*
27         将list2中结点放入newList
28        */
29         nodePos.next = l2;
30         l2 = l2.next;
31       }
32       nodePos = nodePos.next;
33     }
34     nodePos.next = l1 == null ? l2 : l1;
35     return newList.next;
36   }
37
38   /*
39   思路:递归  时间O(n)
40  */
41   public ListNode mergeTwoLists1(ListNode l1, ListNode l2) {
42     if (l1 == null) {
43       return l2;
44     }
45     if (l2 == null) {
46       return l1;
47     }
48     if (l1.val >= l2.val) {
49       l1.next = mergeTwoLists(l1.next, l2);
50       return l1;
51     } else {
52       l2.next = mergeTwoLists(l1, l2.next);
53       return l2;
54     }
55   }
56 }```

0条评论