定义一个链表:
typedef struct Chain {
int value;
struct Chain *next;
} Chain;
在控制台输出链表:
void chainPrint(Chain *chain) {
printf("START -> ");
if (chain != NULL) {
do {
printf("%d -> ", chain->value);
chain = chain->next;
} while (chain != NULL);
}
printf("END.\n");
}
释放在堆上创建的链表
void chainFree(Chain *chain) {
if (chain == NULL) {
return;
}
do {
Chain *tmp = chain->next;
free(chain);
chain = tmp;
} while (chain != NULL);
}
链表的复制
void chainCopy(Chain *src, Chain **dst) {
if (src == NULL) {
*dst = NULL;
return;
}
*dst = malloc(sizeof(Chain));
Chain *tmpDst = *dst;
while (YES) {
tmpDst->value = src->value;
if (src->next != NULL) {
tmpDst->next = malloc(sizeof(Chain));
tmpDst = tmpDst->next;
}else{
tmpDst->next = NULL;
break;
}
src = src->next;
}
}
链表反转。遍历链表的同时,将链表的指向反转。
Chain *chainReverse(Chain *old) {
Chain *new = NULL; // 记录反转后的链表的表头。
Chain *next = NULL; // 中间变量
while (old != NULL) {
next = old->next;
old->next = new;
new = old;
old = next;
}
return new;
}