JasonChang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
 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         // IMPORTANT: Please reset any member data you declared, as
15         // the same Solution instance will be reused for each test case.
16         if(l1 == null && l2 == null)
17             return null;
18         if(l1 == null)
19             return l2;
20         if(l2 == null)
21             return l1;
22         
23         ListNode header = null;
24         ListNode runner = null;
25         while(l1 != null && l2 != null)
26         {
27             if(l1.val < l2.val)
28             {
29                 if(header == null){
30                     header = l1;
31                     runner = header;
32                 }
33                 else{
34                     runner.next = l1;
35                     runner = runner.next;
36                 }
37                 l1 = l1.next;
38             }
39             else
40             {
41                 if(header == null){
42                     header = l2;
43                     runner = header;
44                 }
45                 else{
46                     runner.next = l2;
47                     runner = runner.next;
48                 }
49                 l2 = l2.next;
50             }
51         }
52         if(l1 != null)
53             runner.next = l1;
54         if(l2 != null)
55             runner.next = l2;
56         return header;
57         
58     }
59 }

 

posted on 2013-11-05 12:05  JasonChang  阅读(154)  评论(0编辑  收藏  举报