不点蓝字,我们哪来故事?
Life only come out of the beautiful, did not wait out of the brilliant.
人生只有走出来的美丽,没有等出来的辉煌。
刷题有时需要技巧。
任务:
程序中函数 fun的功能是计算出带有头结点的单向链表中各结点数据域中值之和作为函数值返回。
预期输出:输出链表数据。输出链表数据之和。
源代码:
#include <stdio.h>
#include <stdlib.h>
#define N 8
typedef struct list {
int data;
struct list *next;
} SLIST;
SLIST *creatlist(int *);
void outlist(SLIST *);
int fun(SLIST *h) {
SLIST *p;
int s = 0;
p = h->next;
while (p) {
s += p->data;
p = p->next;
}
return s;
}
int main() {
SLIST *head;
int a[N] = {12, 87, 45, 32, 91, 16, 20, 48};
head = creatlist(a);
outlist(head);
printf("\nsum=%d\n", fun(head));
return 0;
}
SLIST *creatlist(int a[]) {
SLIST *h, *p, *q;
int i;
h = p = (SLIST *) malloc(sizeof(SLIST));
for (i = 0; i < N; i++) {
q = (SLIST *) malloc(sizeof(SLIST));
q->data = a[i];
p->next = q;
p = q;
}
p->next = 0;
return h;
}
void outlist(SLIST *h) {
SLIST *p;
p = h->next;
if (p == NULL)
printf("The list is NULL!\n");
else {
printf("\nHead ");
do {
printf("->%d", p->data);
p = p->next;
} while (p != NULL);
printf("->End\n");
}
}
运行结果: