#include <stdio.h>
#include <stdlib.h>
#define N 10
struct node {
int value;
struct node * next;
};
struct node * chuangjian_link(void);
struct node * count_occurrences(struct node *list, int n);
/* 要求编写函数显示出n在链表中出现的次数 */
int main(void)
{
struct node * head;
int n;
head = chuangjian_link();
printf("你想查找的数据: ");
scanf("%d", &n);
count_occurrences(head, n);
return 0;
}
struct node * chuangjian_link(void)
{
struct node * head;
struct node * temp;
struct node * add_temp;
head = (struct node *) malloc(sizeof(struct node));
printf("请输入你创建的链表的第1个数据: ");
scanf("%d", &head->value);
head->next = NULL;
temp = head;
for (int i=1;i<5;i++) {
add_temp = (struct node *) malloc(sizeof(struct node));
if (add_temp == NULL) {
printf("内存分配失败。\n");
exit (1);
}
printf("请输入该链表的第%d个数据: ", i+1);
scanf("%d", &add_temp->value);
add_temp->next = NULL;
temp->next = add_temp;
temp = temp->next;
}
return head;
}
struct node * count_occurrences(struct node * list, int n)
{
struct node * p;
int i = 0;
/* 开始搜索链表 */
for (p = list; p != NULL; p = p->next) {
if (p->value == n) {
i++;
printf("%d", i);
return p;
}
}
printf("链表里面没有%d!", n);
return NULL;
}