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.
解题思路:
新建一个ListNode进行存储即可,JAVA实现如下:
static public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode listnode=new ListNode(0);
ListNode index=listnode;
while(l1!=null&&l2!=null){
if(l1.val>l2.val){
ListNode temp=l1;
l1=l2;
l2=temp;
}
index.next=new ListNode(l1.val);
index=index.next;
l1=l1.next;
}
if(l1==null)
index.next=l2;
else
index.next=l1;
return listnode.next;
}
C++:
1 class Solution { 2 public: 3 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 4 if (l1 == NULL) 5 return l2; 6 else if (l2 == NULL) 7 return l1; 8 ListNode* start; 9 if (l1->val < l2->val) { 10 start = l1; 11 l1 = l1->next; 12 } 13 else { 14 start = l2; 15 l2 = l2->next; 16 } 17 ListNode* cur = start; 18 while (l1 != NULL&&l2 != NULL) { 19 if (l1->val < l2->val) { 20 cur->next = l1; 21 cur = cur->next; 22 l1 = l1->next; 23 } 24 else { 25 cur->next = l2; 26 cur = cur->next; 27 l2 = l2->next; 28 } 29 } 30 if (l1 == NULL) 31 cur->next = l2; 32 else 33 cur->next = l1; 34 return start; 35 } 36 };