数组重复次数最多的元素递归
Solution:
解:
Required function:
所需功能:
func_occurence ( node *temp) //recursive function
Input:
输入:
A singly linked list whose address of the first node is stored in a pointer, say head and key is the data of which we have to count the number of occurrences.
一个单链表 ,其第一个节点的地址存储在一个指针中,例如head和key是我们必须计算其出现次数的数据。
Output:
输出:
The number of times key occurred in the list, (c)
列表中键出现的次数( c )
Data structure used:
使用的数据结构:
Singly linked list where each node contains a data element say data and the address of the immediate next node say next, with Head holding the address of the first node.
单链列表,其中每个节点包含一个数据元素,例如data ,直接下一个节点的地址说next ,其中Head保留第一个节点的地址。
Pseudo code:
伪代码:
Beginc=0 //global variableif(temp=NULL)print cElse if(temp->data=key)c=c+1;func_occurence(temp->next);End IfEnd If-elseEnd
C程序使用递归计算链接列表中元素的出现次数 (C program to count the number of occurrences of an element in a linked list using recursion)
#include <stdio.h>#include <stdlib.h>typedef struct list //linked list structure{int data;struct list *next;}node;// global variablesint key,c=0;int occurence(node *temp); //function to check occurenceint main(){node *head=NULL,*temp,*temp1;int choice,count;//building the linked listdo{temp=(node *)malloc(sizeof(node));if(temp!=NULL){printf("\nEnter the element in the list : ");scanf("%d",&temp->data);temp->next=NULL;if(head==NULL){head=temp;}else{temp1=head;while(temp1->next!=NULL){temp1=temp1->next;}temp1->next=temp;}}else{printf("\nMemory not avilable...node allocation is not possible");}printf("\nIf you wish to add more data on the list enter 1 : ");scanf("%d",&choice);}while(choice==1);printf("\nEnter the data to find it's occurrence : ");scanf("%d",&key);count =occurence(head);printf("%d occured %d times in the list",key,count);return 0;}//finding occurence of the key valueint occurence(node *temp) {if(temp==NULL)return c;else{if(temp->data==key)c=c+1;occurence(temp->next);}}
Output
输出量
Enter the element in the list : 1If you wish to add more data on the list enter 1 : 1Enter the element in the list : 2If you wish to add more data on the list enter 1 : 1Enter the element in the list : 3If you wish to add more data on the list enter 1 : 1Enter the element in the list : 4If you wish to add more data on the list enter 1 : 1Enter the element in the list : 5If you wish to add more data on the list enter 1 : 0Enter the data to find it's occurrence : 11 occured 1 times in the list
翻译自: /c-programs/count-the-number-of-occurrences-of-an-element-in-a-linked-list-using-recursion.aspx
数组重复次数最多的元素递归