C - 合并两个字符串列表

时间:2013-05-25 19:52:28

标签: c list

我目前有这个算法:

char** mergeLists(char **a, char **b, int sizeA, int sizeB, int *lSize)
{
    char **list = malloc( sizeof(char *) );
    int pA = 0, pB = 0, listSize = 0;

    while (pA != sizeA && pB != sizeB)
    {
        list = realloc(list, sizeof(char *) * (++listSize) );

        if (strcmp(a[pA], b[pB]) < 0)
        {
            list[listSize-1] = a[pA];
            pA++;                
        }
        else
        {   
            list[listSize-1] = b[pB];
            pB++;   
        }    
    }

    *lSize = listSize;

    return list;
}

但似乎有一些错误。我目前正在进行此测试:

char *l1[6];
l1[0] = "a";
l1[1] = "b";
l1[2] = "c";
l1[3] = "d";
l1[4] = "e";
l1[5] = "f";

char *l2[6];
l2[0] = "aa";
l2[1] = "ba";
l2[2] = "ca";
l2[3] = "da";
l2[4] = "ea";
l2[5] = "fa";

int s;
char **l = mergeLists(l1, l2, 6, 6, &s);

int i = 0;
for(i = 0; i < s; i++)
    printf("%s\n", l[i]);

正在打印:

a
aa
b
ba
c
ca
d
da
e
ea
f

缺少第二个列表的最后一项。我认为在while循环的条件下可能会出现一些错误。

我很感激一些帮助。谢谢。

3 个答案:

答案 0 :(得分:6)

您的代码只运行到任一列表的第一端。您需要在末尾再添加两个循环,以包含列表中尚未完全消耗的值。

答案 1 :(得分:1)

像这样解决:

char** mergeLists(char **a, char **b, int sizeA, int sizeB, int *lSize){
    char **list = NULL;
    int pA = 0, pB = 0, listSize = 0;
    int emptyA = 0, emptyB = 0;

    while (pA != sizeA || pB != sizeB){
        list = realloc(list, sizeof(char *) * (++listSize) );

        if(emptyA){
            list[listSize-1] = b[pB++];
            continue;
        }
        if(emptyB){
            list[listSize-1] = b[pA++];
            continue;
        }
        if (strcmp(a[pA], b[pB]) < 0){
            list[listSize-1] = a[pA++];
            if(pA == sizeA)
                emptyA = 1;
        }
        else{
            list[listSize-1] = b[pB++];
            if(pB == sizeB)
                emptyB = 1;
        }
    }

    *lSize = listSize;

    return list;
}

答案 2 :(得分:1)

#include <stdlib.h>
#include <string.h>

char **merge_arrays(char **arrA, char **arrB, size_t sizeA, size_t sizeB, size_t *lSize)
{
    size_t idxA , idxB , idxDst ;
    char **result ;

    result = malloc( (sizeA+sizeB) * sizeof *result );
    if (!result) return NULL;

    for(idxA=idxB=idxDst=0; idxA < sizeA && idxB < sizeB; )
    {
        if (strcmp(arrA[idxA], arrB[idxB]) <= 0) result[idxDst++] = arrA[idxA++];
        else result[idxDst++] = arrB[idxB++];
    }

    if (idxA < sizeA) {
        memcpy (result+idxDst, arrA+idxA, (sizeA-idxA) * sizeof *result);
        idxDst += sizeA-idxA;
        }
    else if (idxB < sizeB) {
        memcpy (result+idxDst, arrB+idxB, (sizeB-idxB) * sizeof *result);
        idxDst += sizeB-idxB;
        }

    *lSize = idxDst;

    return result;
}