旅鸟

导航

0009 合并两个有序链表

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
        ListNode p1 = l1; 
        ListNode p2 = l2;
        ListNode res = new ListNode(0);
        ListNode p = res;
        if(p1 == null && p2 == null){
            return null;
        }
        while(p1 != null || p2 != null){
            int a = p1 != null ? p1.val:Int32.MaxValue;
            int b = p2 != null ? p2.val:Int32.MaxValue;
            int min = a<b?a:b;
            if(p1!= null && min == p1.val){
                ListNode temp = new ListNode(min);
                p.next = temp;
                p = p.next;
                p1 = p1.next;
            }
            if(p2!=null && min == p2.val){
                 ListNode temp = new ListNode(min);
                p.next = temp;
                p = p.next;
                p2 = p2.next;
            }
        }
        return res.next;
    }
}

 

posted on 2018-08-06 13:32  旅鸟  阅读(131)  评论(0编辑  收藏  举报