Mgj又不会了,
比较直接的方法是,先拼接,后排序:
写的又复杂又乱,,而且没写出来,赶紧学大佬怎么写的吧,,,
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
merge it first ,and then sort it
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* pcur= (l1->val <= l2->val ? l1 : l2);
ListNode* head=pcur;
ListNode* pcomp=(l1->val > l2->val ? l1 : l2);
ListNode* pcur_next=NULL;
ListNode* pcomp_next=NULL;
while(pcur->next != NULL && pcomp->next != NULL)
{
if(pcur->val < pcomp->val && (pcur->next)->val > pcomp->val )
{
pcur_next=pcur->next;//save next node
pcomp_next=pcomp->next;
pcur->next=pcomp;
pcomp->next=pcur_next;
pcur=pcur_next;//move pcur
pcomp=pcomp_next;
}
}
return head;
}
};
菜,
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
//merge first
ListNode* pcur= l1;
while(pcur->next != NULL)
{
printf("%d ",pcur->val);
pcur=pcur->next;
}
pcur->next=l2;
//sort it
pcur= l1;
int temp=0;
// while(pcur->next != NULL)
// {
// if()
// }
return l1;
}
};
for for 冒泡,,,
大佬:
mgj真清晰。。。
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode dummy(INT_MIN);
ListNode *tail = &dummy;
while (l1 && l2) {
if (l1->val < l2->val) {
tail->next = l1;
l1 = l1->next;
} else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
tail->next = l1 ? l1 : l2;
return dummy.next;
}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode head(INT_MIN);//create a header?
ListNode *tail = &head;
while(l1!= NULL && l2!= NULL)
{
if(l1->val < l2->val)
{
tail->next=l1;
l1=l1->next;
}else{
tail->next=l2;
l2=l2->next;
}
tail= tail->next;
}
tail->next = l1 ? l1:l2;
return head.next;
}
};
本文探讨了链表数据结构中两种链表的合并及排序方法。通过对比不同实现方式,详细解析了一种高效合并链表的算法,并提供了清晰易懂的代码示例。适合对链表操作感兴趣或需要提升链表处理技能的读者。
1476

被折叠的 条评论
为什么被折叠?



