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

    技术2025-01-29  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)); } }

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

    Processed: 0.010, SQL: 9