题目:
解答:
简单的链表归并方法,提供了递归方式和循环方式两种解法,递归方法效率比较低。
代码:
/**
* 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;
if( l1 -> val == l2 -> val ) {
ListNode *temp1 = l1 -> next;
ListNode *temp2 = l2 -> next;
l1 -> next = l2;
l2 -> next = mergeTwoLists( temp1,temp2 );
return l1;
}
else if( l1 -> val < l2 -> val ) {
ListNode *temp = l1 -> next;
l1 -> next = mergeTwoLists( temp,l2 );
return l1;
}
else
return mergeTwoLists( l2,l1 );
}
// 解法二,循环方式
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
ListNode* head, *p;
if(l1->val > l2->val){
head = l2;
l2 = l2->next;
}else{
head = l1;
l1 = l1->next;
}
p = head;
while(l1 && l2){
if(l1->val > l2->val){
p->next = l2;
l2 = l2->next;
}else{
p->next = l1;
l1 = l1->next;
}
p = p->next;
}
if(l1){
p->next = l1;
}else{
p->next = l2;
}
return head;
}
};
更新会同步在我的网站更新(https://zergzerg.cn/notes/webnotes/leetcode/index.html)