原题:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
两个有序链表的合并,一开始速度很低搞不清楚为什么,后来发现代码里多了一个遍历输出用来检查错误的函数,删了就正常了,结果如下:
Success
Runtime: 8 ms, faster than 100.00% of C++ online submissions for Merge Two Sorted Lists.
Memory Usage: 8.7 MB, less than 100.00% of C++ online submissions for Merge Two Sorted Lists.
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* x1=l1,*x2=l2,*x1h=l1,*x2h=l2;
ListNode* head=(ListNode*)malloc(sizeof(ListNode));
head->next=NULL;
head->val=0;
ListNode* h=head;
while(x1!=NULL&&x2!=NULL){
cout<<x1->val<<x2->val<<endl;
if(x1->val<=x2->val){
h->next=x1;
while(x1->val<=x2->val&&x1!=NULL){
x1=x1->next;
h=h->next;
}
}
else if(x1->val>x2->val){
h->next=x2;
while(x1->val>x2->val&&x2!=NULL){
x2=x2->next;
h=h->next;
}
}
}
if(x1!=NULL){h->next=x1;}
else if(x2!=NULL){h->next=x2;}
return head->next;
}
};