天天看點

單連結清單:求所有不及格人數的累計數

#include<iostream>
#include<malloc.h>
#include <iomanip>
using namespace std;
typedef int ElemType;
#define M 20
typedef struct LNode
{
    ElemType data;  //定義資料與
    struct LNode* next; //指針域
}LNode, * LinkList;
void CreateLink(LinkList& h, ElemType a[], int n)
{
    LinkList s, tc; int i;
    h = (LinkList)malloc(sizeof(LinkList));
    tc = h;
    for (i = 0; i < n; i++)
    {
        s = (LinkList)malloc(sizeof(LinkList)); //頭節點建立
        s->data = a[i];
        tc->next = s;
        tc = s;
    }
    tc->next = NULL;
}
int Count(LinkList sl)
{
    int k = 0;
    LNode* p;
    if (sl->next == NULL)return 0;
    p = sl->next;

    //不及格判斷
    while (p != NULL)
    {
        if (p->data < 60) { k++; }
        p = p->next;
    }
    return k;
}
void main()
{
    int N;
    //cout << "請輸入學生人數:" << endl;
    cout << "學生人數為:";
    cin >> N;
    LinkList head;
    ElemType a[M];
    int i, k;
    cout << "請依次輸入所有學生的成績:" << endl;
    for (i = 0; i < N; i++)
        scanf_s("%d", &a[i]);
    cout << "所有學生的成績依次為:" << endl;
    for (i = 0; i < N; i++)
    {
        cout << a[i] << setw(6);
    }
    cout << endl;
    CreateLink(head, a, N);//建立單連結清單
    k = Count(head);//調用求計數值的函數
    cout << "所有學生的成績中不及格的人數為:" << k << "人";
    cout << endl;
}
      

繼續閱讀