2020年05月02日 23:04 __ _ _ _ _

不点蓝字,我们哪来故事?

**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");    }}

运行结果:

文章配图

文章配图

最后的话:刷题要找自己的不足,然后去专攻。

往期推荐:

五一将至,你有什么计划呢?(删除链表元素) 2020-04-30
文章配图

code.blocks最新下载免安装教程及简单入门 2020-04-29
文章配图

结构体管理、存储学生信息 2020-04-22
文章配图

公众号:程序员Bob

一个正在学习C语言的人,致力于将C讲得更透彻!

点赞关注谢谢你

长按下图二维码关注,和你一起领悟程序员的魅力。

文章配图

点“ 在看 ” 你懂得

文章配图

预览时标签不可点

阅读




__