C语言查找某数据在单链表中出现的次数
【问题描述】接收输入数据创建一个带头结点的单链表,查找某数据在此单链表中出现的次数并输出。
【输入形式】1.链表中数据的数量;2.链表中的数据元素;3.待查找的元素
【输出形式】待查找元素出现的次数
【样例输入】
5
521 3 9 48 6
9
【样例输出】1
#include<stdio.h>
#include<stdlib.h>
struct Data
{
int x;
struct Data *next;
};
#define LEN sizeof(struct Data)
int main()
{
struct Data *creat(int x); //声明函数,函数为:返回指针的函数
void Output(struct Data *head, int x); //声明函数,输出链表
int Statistic(int x, int y, struct Data *head); //声明函数,统计次数
struct Data *head;
int n, x, y;
scanf_s("%d", &n); //输入链表结点数,n
head = creat(n); //创建链表
//Output(head, n); //输出链表
scanf_s("%d", &x); //输入待查找的数据,x
y = Statistic(x, n, head); //调用函数,统计待查找的数据在链表中出现的次数
printf("%d\n", y); //输出结果
system("pause");
return 0;
}
struct Data *creat(int x) //定义函数,创建链表
{
struct Data *head, *p1, *p2;
int n;
n = 1;
p1 = p2 = (struct Data *)malloc(LEN);
head = NULL;
while (n <= x)
{
scanf_s("%d", &p1->x);
if (n == 1)
head = p1;
else
p2->next = p1;
p2 = p1;
p1 = (struct Data *)malloc(LEN);
n++;
}
p2->next = NULL;
free(p1);
return head;
}
void Output(struct Data *head, int x) //定义函数,输出链表
{
struct Data *p;
p = head;
printf("head=%p \n", head);
if (head == NULL)
printf("error! \n");
else
do
{
printf("%d \n", p->x);
printf("%p \n", p->next);
p = p->next;
} while (p != NULL);
}
int Statistic(int x, int y, struct Data *head) //定义函数,统计待查找数出现的次数
{
int z;
struct Data *p;
for (p = head, z = 0; p != NULL; p = p->next) //循环条件亦可更改为:y>0;y--
{
if (p->x == x)
z += 1;
}
return z;
}
运行案例:
说明:
1.源程序代码中有输出模块,目的是为了检验链表的输入数据在链表中存在的正确性;
2.程序亦可直接在主函数中完成,不必使用函数;
3.其中,创建链表所使用的知识点为:返回指针值的函数
定义返回指针值的函数的一般形式为:
类型名 *函数名(参数列表);
注意:空格;
4.malloc函数原型为:
void * malloc(usigned int size);
此函数的作用是在内存的动态存储区中分配一个长度为size的连续空间,返回的指针指向该分配域的开头位置,并且返回不指向任何类型数据的指针(
void * 类型),所以用了强制类型转换。
5.使用malloc函数,需包含头文件#include<stdlib.h>。