-
Notifications
You must be signed in to change notification settings - Fork 0
/
Count nodes of linked list.cpp
107 lines (96 loc) · 1.66 KB
/
Count nodes of linked list.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
//{ Driver Code Starts
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
/* Link list node */
struct node
{
int data;
struct node* next;
node(int x){
data = x;
next = NULL;
}
}*head;
void insert()
{
int n,i,value;
struct node *temp;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&value);
if(i==0)
{
head=new node(value);
head->next=NULL;
temp=head;
continue;
}
else
{
temp->next= new node(value);
temp=temp->next;
temp->next=NULL;
}
}
}
/* Function to print linked list */
void printList(struct node *node)
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
// } Driver Code Ends
/*
Node is defined as
struct node
{
int data;
struct node* next;
node(int x){
data = x;
next = NULL;
}
}*head;
*/
class Solution
{
public:
int count(struct node* head, int search_for)
{
int count=0;
node* temp=head;
while(temp!=NULL){
if(temp->data==search_for){
count++;
}
temp=temp->next;
}
return count;
}
};
//{ Driver Code Starts.
/* Drier program to test above function*/
int main(void)
{
/* Start with the empty list */
int t,k,n,value;
/* Created Linked list is 1->2->3->4->5->6->7->8->9 */
scanf("%d",&t);
while(t--)
{
insert();
scanf("%d",&k);
Solution ob;
value=ob.count(head, k);
printf("%d\n",value);
}
return(0);
}
// } Driver Code Ends