两个非递减有序线性表LA, LB.
现要求装两个线性表进行归并形成线性表LC,且LC依然保持非递减顺序
#include
#include
#include
//表达一
int mergelist1( const char* lap, const char *lbp,char *lc)
{
if(lap == NULL || lbp == NULL)
return -1;
while( *lap != 0 && *lbp != 0)
{
if(*lap <= *lbp)
{
*lc++ = *lap++;
}
else
{
*lc++ = *lbp++;
}
}
while(*lap) *lc++ = *lap++;
while(*lbp) *lc++ = *lbp++;
return 0;
}
//表达二
int mergelist( const char *lap, const char *lbp, char *lc)
{
int i,j; //identify current position of la and lb
if(lap == NULL || lbp == NULL)
return -1;
for(i=0, j=0; lap[i] !=0 && lbp[j]!=0;)
{
if(lap[i] <= lbp[j])
{
*lc++ = lap[i];
++i;
}
else
{
*lc++ = lbp[j];
++j;
}
}
//process the remain part
while(lap[i]) *lc++ = lap[i++];
while(lbp[j]) *lc++ = lbp[j++];
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
char *la = "abcdefg";
char *lb = "abcdefgsdfasfsdfsa";
char *lc;
size_t len;
len = strlen(la) + strlen(lb) + 1;
lc = (char *)malloc(len +1);
if(lc == NULL)
return -1;
memset(lc, 0, len+1);
if(mergelist(la, lb, lc))
{
printf("\n\t\t failure! \n");
return -1;
}
printf("%s", lc);
getchar();
free(lc);
return 0;
}
阅读(1028) | 评论(0) | 转发(0) |