标签:
合并两个有序链表,返回的新链表是通过拼接原来的两个链表得到
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.
考虑以下特殊情况:
为了方便处理,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; } }
标签:
原文地址:http://www.cnblogs.com/hf-cherish/p/4597259.html