Merge Two Sorted Lists
Total Accepted: 95133 Total Submissions: 281996 Difficulty: Easy
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).輪流比較l1與l2的值,較小的值鏈接到新鏈上。如l1->val<=l2->val,將l1鏈接到新鏈上,然後遞增l1。
2).重複1).直到l1或者l2爲空。
3).最後將非空的l1或者l2整個鏈接到新鏈末端,結束。
遞歸:(遞歸的方法簡單,且比較好理解)
/**
* 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;
}else if(l2==NULL){
return l1;
}else{
if(l1->val<=l2->val){
l1->next=mergeTwoLists(l1->next,l2);
return l1;
}else{
l2->next=mergeTwoLists(l1,l2->next);
return l2;
}
}
}
};
非遞歸:
/**
* 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;
}else if(l2==NULL){
return l1;
}
ListNode* head;
if(l1->val<=l2->val){
head=l1;
l1=l1->next;
}else{
head=l2;
l2=l2->next;
}
ListNode* p=head;
while(l1!=NULL&&l2!=NULL){
if(l1->val<=l2->val){
p->next=l1;
p=l1;
l1=l1->next;
}else{
p->next=l2;
p=l2;
l2=l2->next;
}
}
if(l1==NULL){
p->next=l2;
}
if(l2==NULL){
p->next=l1;
}
return head;
}
};