题意:
归并两个排好序的链表
我的思路;
我们没有考虑递归的方法,也没有想到用递归解决,先贴出c++的非递归
/**
* 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 *head,*current,*head_l1,*head_l2;
head;
head_l1 = l1;
head_l2 = l2;
if(l1 == NULL && l2 == NULL) return NULL;
if(l1 == NULL) return l2;
if(l2 == NULL) return l1; // 这里学习一下 表示非空可以用更简答的写法 if(!l1)
if(head_l1->val >= head_l2->val) {
head = head_l2;
current = head_l2;
head_l2 = head_l2->next;
} else {
head = head_l1;
current = head_l1;
head_l1 = head_l1->next;
}
while(1){
//存在一个空了的情况
if(head_l1 == NULL) { current->next = head_l2; break;}
if(head_l2 == NULL) { current->next = head_l1; break;}
//如果都不为空
if(head_l1->val >= head_l2->val) {
current->next = head_l2;
current = current->next;
head_l2 = head_l2->next;
} else {
current->next = head_l1;
current = current->next;
head_l1 = head_l1->next;
}
}
return head;
}
};
但是其实是可以用递归的思想,每一步都表示:将相对小的头的next,指向剩下的两个链的归并,知道两个链表中出现空
ListNode * mergeTwoLists( ListNode * l1, ListNode * l2 )
{
if( !l1 ) return l2;
if( !l2 ) return l1;
if( l1->val < l2->val )
{
l1->next = mergeTwoLists( l1->next, l2 );
return l1;
}
else
{
l2->next = mergeTwoLists( l1, l2->next );
return l2;
}
}