PAT基础编程题目-6-6 求单链表结点的阶乘和

PAT基础编程题目-6-6 求单链表结点的阶乘和

题目详情

题目地址:https://pintia.cn/problem-sets/14/problems/738

解答

C语言版

#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));
		if (p) {
   
			scanf_s("%d", &p->Data);
			p->Next = L;  
			L = p;
		}
	}
	printf("%d\n", FactorialSum(L));

	return 0;
}

int FactorialSum(List L)
{
   
	int sum =0, product;
	while(L) {
   
		product = 1; //乘积
		for (int i = 2; i <= L->Data; i++)
		{
   
			product = product * i;
		}
		sum = sum + product;
		L = L->Next;
	}
	return sum;
}

C++版

#include<iostream>
using namespace std;

typedef struct Node {
   
	int Data;
	struct Node* Next;
}Node, * List;

int FactorialSum(List L);
int main() {
   
	int n;
	cin >> n;
	List L=NULL, p;
	while (n--) {
   
		p = (Node*)malloc(sizeof(Node));
		if (p) {
   
			cin >> p->Data;
			p->Next = L;
			L = p;
		}
	}
	cout << FactorialSum(L);
	return 0;
}

int FactorialSum(List L)
{
   
	int sum = 0, product;
	while (L) {
   
		product = 1; //乘积
		for (int i = 2; i <= L->Data; i++)
		{
   
			product = product * i;
		}
		sum = sum + product;
		L = L->Next;
	}
	return sum;
}

Java版

public class Main{
   
	
	private static class Node {
   
		int Data;
		Node Next;
	}
	
	private static int FactorialSum(Node L) {
   
		int sum = 0;
		int product;
		while(L!=null) {
   
			product = 1;
			for (int i = 2; i <= L.Data; i++) {
   
				product = product * i;
			}
			sum = sum +product;
			L = L.Next;
		}
		return sum;
	}

	public static void main(String[] args) {
   
		int n;
		Node L= null;
		Scanner scanner = new Scanner(System.in);
		if(scanner.hasNext()) {
   
			n = scanner.nextInt();
			for (int i = 0; i < n; i++) {
   
				Node p = new Node();
				p.Data = scanner.nextInt();
				p.Next = L;
				L = p;
			}
		}
		scanner.close();
		System.out.println(FactorialSum(L));

	}

}

创作不易,喜欢的话加个关注点个赞,谢谢谢谢谢谢!

全部评论

相关推荐

粗心的雪碧不放弃:纯学历问题,我这几个月也是一直优化自己的简历,后来发现优化到我自己都觉得牛逼的时候,发现面试数量也没有提升,真就纯学历问题
点赞 评论 收藏
分享
在评审的大师兄很完美:像这种一般就是部门不匹配 转移至其他部门然后挂掉 我就是这样被挂了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务