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.
将两个已排好序的链表合并,每次比较两个链表首位的大小,将较小的一位放入新的链表中,并在原链表中去掉首位,依次比较知道其中一个链表
为空,将另一个列表剩余的元素接到新链表的尾部,所得新链表即为两个链表的合并。
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode d(INT_MIN);
ListNode *tail = &d;
while(l1 && l2){
if(l1.val > l2.val){
tail->next = l2;
l2 = l2->next;
}
else{
tail->next = l1;
l1 = l1->next;
}
tail = tail->next;
}
tail->next = l1 ? l1 : l2;
return d.next;
}
};