这道题目和合并有序数组得思路是基本上一致的。就是每次选两个链表中的较小值。
注意当一个链表中的元素被选空了以后,剩下都要选择另一个链表里的元素
c++
class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { // write code here if(l1==NULL)return l2; if(l2==NULL)return l1; ListNode* ans=new ListNode(-1); ListNode* now = ans; while( l1!=NULL || l2!=NULL ) { if( l2 == NULL || (l1 != NULL && (l1->val) <= (l2->val)) ) //l2链表中的数全部用完了就填l1数组中的数 或l1数组中的数没有用完,并且l1数组的数大 { now->next = l1; l1 = l1->next; } else { now->next = l2; l2 = l2->next; } now = now->next; } now->next=NULL; return ans->next; } };
java
import java.util.*; public class Solution { public ListNode mergeTwoLists (ListNode l1, ListNode l2) { // write code here if(l1== null)return l2; if(l2== null)return l1; ListNode ans=new ListNode(-1); ListNode now = ans; while( l1!=null || l2!= null ) { if( l2 == null || (l1 != null && (l1.val) <= (l2.val)) ) //l2链表中的数全部用完了就填l1数组中的数 或l1数组中的数没有用完,并且l1数组的数大 { now.next = l1; l1 = l1.next; } else { now.next = l2; l2 = l2.next; } now = now.next; } now.next = null; return ans.next; } }
python
class Solution: def mergeTwoLists(self , l1 , l2 ): # write code here if l1== None: return l2 if l2== None: return l1 ans = ListNode(-1); now = ans; while l1!=None or l2!= None: if l2 == None or (l1 != None and (l1.val) <= (l2.val)): #l2链表中的数全部用完了就填l1数组中的数 或l1数组中的数没有用完,并且l1数组的数大 now.next = l1 l1 = l1.next else: now.next = l2 l2 = l2.next now = now.next; now.next = None; return ans.next;