题目描述:
将两个排序链表合并为一个新的排序链表
样例
给出 1->3->8->11->15->null,2->null, 返回 1->2->3->8->11->15->null。
思路分析:
和插入排序一模一样。
ac代码:
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = 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 *r,*dummy;
dummy=new ListNode(0);
dummy->next=l2;
l2=dummy;
while(l1!=NULL) //把l1中的元素 插入到l2中。
{
r=l2;
while(r->next!=NULL && r->next->val<l1->val)
{
r=r->next;
}
ListNode *temp=l1->next;
l1->next=r->next;
r->next=l1;
l1=temp;
}
return l2->next;
}
};