码迷,mamicode.com
首页 > 其他好文 > 详细

Merge Two Sorted Lists

时间:2014-11-09 16:34:47      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   color   sp   for   div   on   

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

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 }

 

Merge Two Sorted Lists

标签:des   style   blog   io   color   sp   for   div   on   

原文地址:http://www.cnblogs.com/luckygxf/p/4085283.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!