이 문제에서는 연결 목록이 제공됩니다. 우리의 임무는 링크드 리스트에서 주어진 숫자가 몇 번인지 셀 수 있는 함수를 만드는 것입니다.
문제를 이해하기 위해 예를 들어보겠습니다.
입력
Linked list = 10-> 50 -> 10 -> 20 -> 100 -> 10, int = 10
출력
3
설명 - 10번은 연결 리스트에서 3번 나옵니다.
이 문제에 대한 해결책은 간단합니다. 연결 목록을 탐색하고 카운터를 증가시키면 현재 노드 값이 주어진 숫자와 같습니다.
연결 목록의 노드에 대한 루프는 반복과 재귀를 사용하여 수행할 수 있으며 문제를 해결하는 두 가지 방법을 모두 보여줍니다.
반복을 사용하여 솔루션을 설명하는 프로그램
예시
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
};
void push(Node** head_ref, int new_data) {
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int countInt(Node* head, int search_for) {
Node* current = head;
int intCount = 0;
while (current != NULL) {
if (current->data == search_for)
intCount++;
current = current->next;
}
return intCount;
}
int main() {
Node* head = NULL;
push(&head, 10);
push(&head, 40);
push(&head, 10);
push(&head, 50);
push(&head, 20);
push(&head, 90);
push(&head, 10);
cout<<"The count of 10 in the linked list is "<<countInt(head, 10);
return 0;
} 출력
연결 목록에서 10의 개수는 3입니다.
재귀를 사용하여 솔루션을 설명하는 프로그램,
예시
#include <iostream>
using namespace std;
int intCount = 0;
class Node {
public:
int data;
Node* next;
};
void push(Node** head_ref, int new_data) {
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int countInt(struct Node* head, int key){
if (head == NULL)
return intCount;
if (head->data == key)
intCount++;
return countInt(head->next, key);
}
int main() {
Node* head = NULL;
push(&head, 10);
push(&head, 40);
push(&head, 10);
push(&head, 50);
push(&head, 20);
push(&head, 90);
push(&head, 10);
cout<<"The count of 10 in the linked list is "<<countInt(head, 10);
return 0;
} 출력
The count of 10 in the linked list is 3