*给定一个单链表,其数据元素为正整数,要求实现一个函数,可输出该表中值能被3整除的结点的个数;若表空,输出0。
*统计单链表中能被3整除的结点的个数
* 输入样例:
8
1 3 4 5 6 7 8 9
第一行的8为单链表的长度,第二行为各个结点的数据值。
输出样例:
3
#include <iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100
typedef int Status;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode, *LinkList;
Status InitList(LinkList &L)
{
L = new LNode;
L->next = NULL;
return OK;
}
void CreateList(LinkList L, int n)
{
LNode *p, *r;
int i;
r = L;
for(i = 0; i < n; ++i)
{
p = new LNode;
cin >> p->data;
r->next = p;
r = p;
}
r->next = NULL;
}
/* 请在这里填写答案 */
int Count_3(LinkList L)
{
int j = 0;
LNode *p = L->next;
while (p)
{
if (p->data % 3 == 0)
j++;
p = p->next;
}
return j;
}
int main() {
LinkList La = NULL;
int n;
InitList(La);
cin >> n;
CreateList(La, n);
cout << Count_3(La);
return 0;
}
统计单链表中能被3整除的结点的个数
最新推荐文章于 2023-01-08 14:37:28 发布