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

merge two sorted lists

时间:2015-06-24 22:28:44      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

1. Question

合并两个有序链表,返回的新链表是通过拼接原来的两个链表得到

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.

2. Solution(O(m+n))

 考虑以下特殊情况:

  • 链表为空:都为空,某个为空
  • 两链表排序方式不同

为了方便处理,new一个空节点作为结果链表的头,其指向l1,然后再将l2合并到该链表中

技术分享
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    //true is non-descending, false is descending
    public boolean compare( int a, int b ){
        if( a>b )    return false;
        return true;
    }
    
    public ListNode reverseList( ListNode l ){
        if( l==null || l.next==null )    return l;
        ListNode p = l;
        ListNode q = l.next;
        l.next = null;
        do{
            ListNode next = q.next;
            q.next = p;
            p = q;
            q = next;            
        }while( q!=null);
        return p;
    }
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if( l1==null )    return l2;
        if( l2==null )    return l1;        
        
        //if the order of the two lists is different, reverse List l2
        if( l1.next!=null && l2.next!=null && compare(l1.val, l1.next.val) != compare(l2.val,l2.next.val) )
            l2 = reverseList( l2 );
        
        //if the order of the two lists is same
        boolean order;
        if( l1.next!=null ) order = compare(l1.val,l1.next.val );
        else if( l2.next != null )    order = compare( l2.val, l2.next.val );
        else order = true;
        // p is the present end pointer of the result list, l2 is the present inserting pointer of list l2.
        ListNode p =new ListNode(0);
        p.next = l1;
        ListNode res = p;
        do{
            if( compare(p.next.val,l2.val) == order )
                p = p.next;
            else{
                ListNode q = l2;
                for( ; q.next!=null && compare(p.next.val, q.next.val)!=order; q=q.next );
                ListNode temp = p.next;
                p.next = l2;
                l2 = q.next;
                q.next = temp;
                p = temp;
            }
        }while( p.next!=null && l2!=null );
        
        if( l2!=null )
            p.next = l2;
        return res.next;
    }
}
View Code

 

merge two sorted lists

标签:

原文地址:http://www.cnblogs.com/hf-cherish/p/4597259.html

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