1.两个有序单链表的合并
typedef struct ListNode{
int val;
ListNode* next;
}ListNode;
ListNode* mergeList(ListNode* pHead1,ListNode* pHead2){
if (pHead1==NULL) return pHead2;
if (pHead2 == NULL) return pHead1;
ListNode* pMergeHead = NULL;
if (pHead1->val < pHead2->val){
pMergeHead = pHead1;
pMergeHead->next = mergeList(pHead1->next,pHead2);
}
else{
pMergeHead = pHead2;
pMergeHead->next = mergeList(pHead2->next,pHead1);
}
return pMergeHead;
}
2,.两个有序数组的合并
从后往前合并,假设第一个数组足够大,可以容纳合并后的数组。
#define MAXN 1024
void combine(int *a, int *b, int len1, int len2){
if (a == NULL || b == NULL || (len1 + len2) > MAXN)
return;
int new_point;
int a_point = len1 - 1;
int b_point = len2 - 1;
new_point = len1 + len2 - 1;//总的长度
while (a_point>=0&&b_point>=0){
if (a[a_point] > b[b_point]){
a[new_point--] = a[a_point--];
}
else{
a[new_point--] = b[b_point--];
}
}
while (a_point >= 0){
a[new_point--] = a[a_point--];
}
while (b_point >= 0){
a[new_point--] = b[b_point--];
}
return;
}