PAT练习基础编程题目之求单链表结点的阶乘和

求单链表结点的阶乘和

导语:链表一直是我的弱项,做这道题做了比较久,程序本身不难,只是对指针的理解不到位,况且很久没有接触指针相关,遗忘了不少。风萧萧兮易水寒,壮士一去兮不复还。
- 本题要求实现一个函数,求单链表L结点的阶乘和。这里默认所有结点的值非负,且题目保证结果在int范围内。
- 函数接口定义:
int FactorialSum( List L );

typedef struct Node *PtrToNode;
struct Node {
    int Data; /* 存储结点数据 */
    PtrToNode Next; /* 指向下一个结点的指针 */
};
typedef PtrToNode List; /* 定义单链表类型 */
int FactorialSum( List L );
int main()
{
    int N, i;
    List L, p;
    scanf("%d", &N);
    L = NULL;
    for ( i=0; i<N; i++ ) {
        p = (List)malloc(sizeof(struct Node));
        scanf("%d", &p->Data);
        p->Next = L;  L = p;
    }
    printf("%d\n", FactorialSum(L));
    return 0;
}
int fun(int n){
    if(n==0 || n==1)
        return 1;
    else
        return n*fun(n-1);
}
int FactorialSum( List L ){
    int sum = 0;
    while(L!=NULL){
        int m = fun(L->Data);
        sum += m;
        L = L->Next;
    }
    return sum;
}

结束语:回头还得好好看看指针,语法这里了解的不透彻,之前一直在做Java,学c语言的那会也不够认真,不管了,天将降大任于斯人也,必先苦其心志,饿其体肤,空乏其身。。。。

你可能感兴趣的:(函数,指针,单链表,PAT习题)