/cocowy的编程之旅
leetcode-21
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
*/
目前已知的解法:
1 链表归并
2 递归法
3.直接选择排序(冒泡)
*/
- 归并法,通过构造第三个链表头指针,使其完成排序。
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(l1==NULL) return l2;
if(l2==NULL) return l1;
struct ListNode *head,*p;
head=(struct ListNode*)malloc(sizeof(struct ListNode));
head->next=NULL;
p=head;
while(l1&&l2)
{
if(l1->val<l2->val)
{
p->next=l1;
l1=l1->next;
p=p->next;
}
else
{
p->next=l2;
l2=l2->next;
p=p->next;
}
}
p->next=(l1!=NULL)?l1:l2;//
return head->next;
}
- 递归法
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(l1==NULL) return l2;
if(l2==NULL) return l1;
struct ListNode *ret=NULL;
if(l1->val<l2->val)
{
ret=l1;
ret->next=mergeTwoLists(l1->next,l2);
}
else
{
ret=l2;
ret->next=mergeTwoLists(l1,l2->next);
}
return ret;
}
3.归并冒泡排序法
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(l1==NULL)
return l2;
if(l2==NULL)
return l1; //l1不为空且l2为空
struct ListNode* p=l1;
struct ListNode* q;
//将两个链表首位相接直接构成一个链表
while(p->next!=NULL)
p=p->next;
p->next=l2;
//直接排序排列val值
int temp;
for(p=l1;p;p=p->next)
{
for(q=p->next;q;q=q->next)
{
if(p->val>q->val)
{
temp=p->val;
p->val=q->val;
q->val=temp;
}
}
}
return l1;
}