辛辛苦苦写的的代码,运行超出时间限制!内心无比悲伤,怎一个“愁”字了得?记录一下。
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
//
// An highlighted block
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == NULL && l2==NULL){
return NULL;
}
if(l1==NULL && l2!=NULL){
return l2;
}
if(l1!=NULL && l2==NULL){
return l1;
}
ListNode* cur = l1;
ListNode* tail;
while(cur->next != NULL){
cur = cur->next;
}
tail = cur; //指向末尾结点;tail->next是NULL
//连接l1和l2
tail->next = l2;
int count=0;
int len;
cur = l1;
while(cur!=NULL){
++count;
cur = cur->next;
}
cout<<"count:"<<count<<endl;
len = count; //链表size
//冒泡排序
cur = l1->next;
ListNode* pre = l1;
int temp;//临时来存储变量
for(int i=0;i<len-1;i++){
for(int j=0;j<len-1-i;j++){
if(cur->val < pre->val){
temp = cur->val;
cur->val = pre->val;
pre->val = temp;
}
pre = cur;
cur = cur->next;
}
cur = l1->next;
pre = l1;
}
return l1;
}
};