Merge Two Sorted Lists

 1 public class Solution {
 2     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
 3         ListNode safe = new ListNode(-1);
 4         ListNode pre = safe;
 5         while(l1!=null && l2!=null){
 6             if(l1.val<l2.val){
 7                 pre.next = l1;
 8                 l1 = l1.next;
 9             }
10             else{
11                 pre.next = l2;
12                 l2 = l2.next;
13             }
14             pre = pre.next;
15         }
16         if(l1!=null){
17             pre.next = l1;
18         }
19         if(l2!=null){
20             pre.next = l2;
21         }
22         return safe.next;
23     }
24 }
View Code

 

posted @ 2014-02-06 14:31  krunning  阅读(214)  评论(0编辑  收藏  举报