题外话:这是我的第一篇博客,希望我能坚持下去,也希望我的一些小小的感悟能够帮助到别人。
在测试或者调试中,我们经常需要创建变长数组或者链表,用它来验证自己的算法函数是否正确。比如我做了一个链表的反序函数reverse(),我需要手动创建一个链表来验证reverse函数是否工作正常,达到期望。或者我需要产生一个数组,来验证我写的冒泡排序算法是否正确。等等诸如此类的。
对于链表生成,之前我都是用逐个节点依次申请内存然后再链接。这样做的效率较低,而且需要对每次的malloc去做NULL判断,代码比较繁琐而且丑陋。多次改进后,我找到一个方法就是首先输入数组/链表长度,然后一次性申请好内存,再做赋值/链接。这样做的效率就明显提高,且代码简洁易用。
话不多说,上代码体。
console输入格式 length val0 val1 val2
例如我要生成一个数组,长度是5, 数组元素的值依次为 3 6 9 4 7, 那么我可以直接输入 5 3 6 9 4 7 然后回车。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/* Put your function here */
int main(int argc, char *argv[])
{
int i;
unsigned int len;
int *vector = NULL;
/* get the array lenth from input */
scanf("%u", &len);
vector = (int *)malloc(len * sizeof(int));
if (NULL == vector) {
return 1;
}
/* get the array value from input */
for (i=0; i<len; i++) {
scanf("%d", &vector[i]);
}
/* function call */
free(vector);
return 0;
}
上面是生成数组的框架。我们拿这个做例子来做一个冒泡排序的测试。我们把冒泡算法bubblesort()函数加入到上面的框架中,然后编译成可执行文件,就可以测试了。下面是加上bubblesort函数后的代码,编译后可以直接用来验证。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void bubblesort(int *array, unsigned int len)
{
int i, j, tmp;
if (NULL == array) {
return;
}
for (i=0; i<len; i++) {
for (j=i+1; j<len; j++) {
if (array[i] > array[j]) {
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
}
}
void printarray(int *array, unsigned int len)
{
int i;
if (NULL == array) {
return;
}
for (i=0; i<len; i++) {
printf("%d ", array[i]);
}
}
int main(int argc, char *argv[])
{
int i;
unsigned int len;
int *vector = NULL;
/* get the array lenth from input */
scanf("%u", &len);
vector = (int *)malloc(len * sizeof(int));
if (NULL == vector) {
return 1;
}
/* get the array value from input */
for (i=0; i<len; i++) {
scanf("%d", &vector[i]);
}
bubblesort(vector, len);
printarray(vector, len);
free(vector);
return 0;
}
测试结果:
-bash-4.1$ gcc bubbletest.c -o bubbletest
-bash-4.1$ ./bubbletest
10 2 7 3 1 9 6 4 10 5 8
1 2 3 4 5 6 7 8 9 10