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求和。

转载于:https://www.cnblogs.com/pxy-1999/p/10255529.html

### PTA 单链表节点阶乘 C/C++/Python 实现 #### 使用 C++ 计算单链表节点值的阶乘 为了实现这一功能,在C++中可以定义一个结构体`Node`表示链表中的结点,其中包含数据成员`data`存储该结点的数据以及指针成员`next`指向下一个结点。接着创建函数`factorialSum`遍历整个列表并累加各结点数据对应的阶乘。 ```cpp #include <iostream> using namespace std; struct Node { int data; struct Node* next; }; // Function to calculate factorial of a number n. int fact(int n) { if (n == 0 || n == 1) return 1; else return n * fact(n - 1); } // Function that returns sum of factorials present at each node in the linked list pointed by head. long long factorialSum(struct Node* head) { long long sum = 0; while (head != NULL) { sum += fact(head->data); // Add up all the factorials from nodes into variable 'sum' head = head->next; // Move on to check next element/node within this Linked List structure } return sum; } ``` 上述代码实现了计算单链表内所有元素对应阶乘的功能[^3]。 #### Python 版本实现相同逻辑 对于Python而言,则不需要显式声明类型,因此可以直接利用类(Class)`ListNode`模拟链表行为,并通过迭代器访问各个位置上的对象实例完成同样的任务: ```python class ListNode: def __init__(self, val=0, nxt=None): self.val = val self.next = nxt def get_factorial(num): result = 1 for i in range(2, num + 1): result *= i return result def factorial_sum(head): total = 0 current_node = head while current_node is not None: total += get_factorial(current_node.val) current_node = current_node.next return total ``` 这段脚本同样完成了对输入链表中每一个整数值取其阶乘并将它们相加以获得最终的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值