Merge Two Sorted Lists

归并两个有序序列为一个有序序列

Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
14         ListNode i = l1;
15         ListNode j = l2;
16         ListNode k ;
17         ListNode end;
18         //有空序列
19         if(null == l1 && null ==l2)
20             return null;
21         else if(null == l1 || null == l2){
22             return null == l1 ? l2:l1; 
23         }
24         //没有空序列
25         if(i.val < j.val){
26             k = new ListNode(i.val);
27             k.next = null;
28             i = i.next;
29         }else
30         {
31             k = new ListNode(j.val);
32             k.next = null;
33             j = j.next;
34         }
35         end = k;
36         
37         while(null != i && null != j){
38             ListNode temp;
39             if(i.val < j.val){
40                 temp = new ListNode(i.val);
41                 
42                 i = i.next;
43             }else{
44                 temp =  new ListNode(j.val);
45                 j = j.next;
46             }
47             temp.next = null;
48             end.next = temp;
49             end = temp;
50         }
51         if(null != i){
52             while(null != i){
53                 ListNode temp = new ListNode(i.val);
54                 temp.next = null;
55                 end.next = temp;
56                 end = temp;
57                 i = i.next;
58             }
59         }
60         if(null != j){
61             while(null != j){
62                 ListNode temp = new ListNode(j.val);
63                 temp.next = null;
64                 end.next = temp;
65                 end = temp;
66                 j = j.next;
67             }
68         }
69         
70         return k;
71     }
72 }
原文地址:https://www.cnblogs.com/luckygxf/p/4085283.html