将两个排序链表合并为一个新的排序链表
样例
给出 1->3->8->11->15->null
,2->null
, 返回 1->2->3->8->11->15->null
。
解题思路:直接将一个链表看成插入排序的中间过程,插入另一个链表即可,代码就是插入排序改改。
class Solution {
public:
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
// write your code here
ListNode *t=new ListNode(0),*head=l2;
t->next=l1;
while(head!=NULL){
ListNode *pre=t;
while (pre->next != NULL && pre->next->val < head->val) {
pre = pre->next;
}
ListNode *tem=head->next;
head->next=pre->next;
pre->next=head;
head=tem;
}
return t->next;
}