coding
unsky
deepdim
thought

Merge Two Sorted Lists

id21. Merge Two Sorted Lists Add to List QuestionEditorial Solution My Submissions
Total Accepted: 185619
Total Submissions: 488183
Difficulty: Easy
Contributors: Admin
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* 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) {
if(l1==NULL)return l2;
if(l2==NULL)return l1;
ListNode *result=new ListNode(-1);
ListNode *head=result;
while(l1!=NULL&&l2!=NULL)
{
if(l1->val<l2->val)
{ ListNode *node=l1;
result->next=node;
result=result->next;
l1=l1->next;
}
else if(l1->val>=l2->val){
ListNode *node=l2;
result->next=node;
result=result->next;
l2=l2->next;
// cout<<l2->val<<" "<<l1->val<<endl;
}
}
if(l1&&l2)
return head->next;
else
{
if(l1==NULL)
{
result->next=l2;}
else if(l2==NULL)
result->next=l1;
return head->next;
}
delete result;
}
};
坚持原创技术分享,您的支持将鼓励我继续创作!