合并两个排序链表

将两个排序链表合并为一个新的排序链表

样例

给出 1->3->8->11->15->null2->null, 返回 1->2->3->8->11->15->null

解题思路:新开一个新链表,比较两个链表元素的大小,一次向新链表中添加即可。

 1 /**
 2  * Definition for ListNode.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int val) {
 7  *         this.val = val;
 8  *         this.next = null;
 9  *     }
10  * }
11  */ 
12 public class Solution {
13     /**
14      * @param ListNode l1 is the head of the linked list
15      * @param ListNode l2 is the head of the linked list
16      * @return: ListNode head of linked list
17      */
18     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
19         // write your code here
20         ListNode result = new ListNode(0);
21         ListNode head = result;
22         while(l1!=null && l2 !=null){
23             if(l1.val <= l2.val){
24                 result.next = l1;
25                 l1 = l1.next;
26             }else {
27                 result.next  = l2;
28                 l2 = l2.next;
29             }
30             result = result.next;
31         }
32         if(l1 == null )   result.next = l2;
33         if(l2 == null )   result.next = l1;
34         
35         return head.next;
36     }
37 }

 

posted @ 2015-11-26 03:15  码代码的banana  阅读(252)  评论(0编辑  收藏  举报