數組重復次數最多的元素遞歸
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:
偽代碼:
Begin
c=0 //global variable
if(temp=NULL)
print c
Else
if(temp->data=key)
c=c+1;
func_occurence(temp->next);
End If
End If-else
End
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 variables
int key,c=0;
int occurence(node *temp); //function to check occurence
int main()
{
node *head=NULL,*temp,*temp1;
int choice,count;
//building the linked list
do
{
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 value
int 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 : 1
If you wish to add more data on the list enter 1 : 1
Enter the element in the list : 2
If you wish to add more data on the list enter 1 : 1
Enter the element in the list : 3
If you wish to add more data on the list enter 1 : 1
Enter the element in the list : 4
If you wish to add more data on the list enter 1 : 1
Enter the element in the list : 5
If you wish to add more data on the list enter 1 : 0
Enter the data to find it's occurrence : 1
1 occured 1 times in the list
翻譯自: https://www.includehelp.com/c-programs/count-the-number-of-occurrences-of-an-element-in-a-linked-list-using-recursion.aspx
數組重復次數最多的元素遞歸