PTA基礎編程題目集6-6求單鏈表結點的階乘和(函數題)


本題要求實現一個函數,求單鏈表L結點的階乘和。這里默認所有結點的值非負,且題目保證結果在int范圍內。

函數接口定義:

1 int FactorialSum( List L );

其中單鏈表List的定義如下:

1 typedef struct Node *PtrToNode;
2 struct Node {
3     int Data; /* 存儲結點數據 */
4     PtrToNode Next; /* 指向下一個結點的指針 */
5 };
6 typedef PtrToNode List; /* 定義單鏈表類型 */

裁判測試程序樣例:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 typedef struct Node *PtrToNode;
 5 struct Node {
 6     int Data; /* 存儲結點數據 */
 7     PtrToNode Next; /* 指向下一個結點的指針 */
 8 };
 9 typedef PtrToNode List; /* 定義單鏈表類型 */
10 
11 int FactorialSum( List L );
12 
13 int main()
14 {
15     int N, i;
16     List L, p;
17 
18     scanf("%d", &N);
19     L = NULL;
20     for ( i=0; i<N; i++ ) {
21         p = (List)malloc(sizeof(struct Node));
22         scanf("%d", &p->Data);
23         p->Next = L;  L = p;
24     }
25     printf("%d\n", FactorialSum(L));
26 
27     return 0;
28 }
29 
30 /* 你的代碼將被嵌在這里 */

輸入樣例:

3

5 3 6

輸出樣例:

846

 1 int FactorialSum( List L )
 2 {
 3     int i;
 4     int sum = 0;
 5     while(L!=NULL)
 6     {    
 7         int num = 1;
 8         for(i=1;i<=L->Data;i++)
 9         {
10             num=num*i; //求階乘
11         }
12         sum+=num;  //每一個結點階乘的和
13         L=L->Next;  //進行下一個結點的階乘求和
14 
15     }
16     return sum;
17 }

將鏈表的數據域比對成一個數組更好理解,L->Data就是一個具體數。用num作為階乘,用sum求和。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM