資料結構 函式題6.15
阿新 • • 發佈:2020-12-23
6-15 求單鏈表結點的階乘和 (15分)
本題要求實現一個函式,求單鏈表L結點的階乘和。這裡預設所有結點的值非負,且題目保證結果在int範圍內。
函式介面定義:
int FactorialSum( List L );
其中單鏈表List的定義如下:
typedef struct Node PtrToNode;
struct Node {
int Data; / 儲存結點資料 /
PtrToNode Next; / 指向下一個結點的指標 /
};
typedef PtrToNode List; / 定義單鏈表型別 */
裁判測試程式樣例:
#include <stdio.h>
#include <stdlib.h>
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;
}
/* 你的程式碼將被嵌在這裡 */
輸入樣例:
3
5 3 6
輸出樣例:
846
int FactorialSum( List L )
{
int cnt=0,sum=1;;
while (L)
{
for(int i=1;i<=L->Data;i++)
sum=sum*i;
cnt+=sum;
sum=1;
L=L->Next;
}
return cnt;
}