//输出一个整数序列中与制定数字相同的个数
//输入:包含三行:1.n整数序长度;2.n个整数,以空格隔开;3. 指定的整数m
#include<stdio.h>
#include<stdlib.h>
typedef struct node//创建单链表
{
int data;//数据
struct node*next;//指针
}Node;
int count(Node *head,int m);//函数声明 遍历链表
void destroy(Node*head);// 遍历链表 释放空间
int main(void)
{
int n,m ,x;
scanf("%d",&n);//输入n
Node*head = NULL,*s,*tail;//声明指针变量作为头指针 *s指向x *tail指向链表表尾
for(int i=1;i<=n;i++)
{
scanf("%d",&x);
s=(Node*)malloc(sizeof(Node));//为x分配节点空间
s->data=x;// s指向新分配空间
if(i==1)//如果是链表第一个 头指针指向s 其余是tail
head=s;
else
tail->next=s; //移动s向下一位
tail=s; //tail指向新表尾
}
tail->next=NULL; //创建成功
scanf("%d",&m);
int c=count(head,m);//遍历链表函数
printf("%d\n",c);
destroy(head);
return 0;
}
int count(Node *head,int m)
{
int c=0;//计数器
Node*p=head;
while(p)
{
if(p->data==m)c++;//p指向数据与m相同 c自增
p=p->next;//p后移
}
return c;
}
void destroy(Node*head)//释放链表数据
{
Node*p=head,*q;
while(p)
{
q=p;
p=p->next;
free(q);
}
}
事例: