PTA习题解答 基础编程题目集 6-6 求单链表结点的阶乘和

题目:

本题要求实现一个函数,求单链表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;
}

/* 你的代码将被嵌在这里 */

答案:

int FactorialSum( List L )
{
	int sum=0;//阶乘累积和 
	while(L!=NULL)//从第一个结点开始遍历整个链表 
	{	
		int t=1;
		for(int i=1; i<=L->Data; i++)
			t *= i;//求当前节点数据的阶乘 
		sum += t;//求当前遍历完所有节点的阶乘和 
		L = L->Next;	
	}
	return sum;
}

心得:

做这个题目的时候,第一次编译没有通过,算法思想是对的,但是对链表的知识有点忘记,随后查询了一些链表的知识,改正过来了。

### C语言实现单链表节点的阶乘 #### 定义单链表结构 为了计算单链表中各节点存储数值的阶乘,首先定义一个简单的单链表节点结构 `Node`。该结构包含两个部分:一个是用于保存整数的数据域;另一个是指向下一个节点的指针。 ```c #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; ``` #### 创建并初始化链表 创建函数来构建带有初始值的单链表,并通过循环读取输入直到遇到特定终止条件为止。这里假设以负数表示结束输入[^1]。 ```c void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } ``` #### 计算阶乘辅助函数 编写一个递归或迭代版本的阶乘计算器,以便稍后调用它处理每一个节点中的数据。 ```c unsigned long factorial(int n){ unsigned long fact = 1; while(n>0){ fact *= n--; } return fact; } ``` #### 主逻辑——遍历链表解总 最后,在主程序里依次访问各个节点,利用之前准备好的阶乘函数累加得到最终的结果。 ```c int sumOfFactorials(struct Node *node) { int sum = 0; while(node != NULL){ sum += factorial(node->data); node = node->next; } return sum; } // 测试代码片段 int main(){ struct Node* head = NULL; // 假设从标准输入获取一系列正整数构成链表... int num; do{ scanf("%d", &num); if(num >= 0) push(&head, num); }while(num>=0); printf("Sum of factorials is %d\n", sumOfFactorials(head)); return 0; } ``` 此段代码实现了接收一组非负整数形成单链表,并输出这些数字对应的阶乘累积的功能。注意实际应用时可能需要考虑大数溢出等问题以及更严谨的边界情况测试[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值