C++のリンクリストで特定のintが発生する回数をカウントする関数を記述します
この問題では、リンクリストが提供されます。私たちのタスクは、リンクリストで特定の数が発生した回数をカウントできる関数を作成することです。
問題を理解するために例を見てみましょう
入力
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
-
C++のリンクリストの代替ノードの合計
この問題では、リンクリストが表示されます。私たちのタスクは、リンクリストの代替ノードの合計を出力することです。 リンクリストは、リンクを介して相互に接続された一連のデータ構造です。 では、問題に戻りましょう。ここでは、リンクリストの代替ノードを追加します。これは、ノードが位置0、2、4、6、…であることを追加することを意味します 問題を理解するために例を見てみましょう。 入力 4 → 12 → 10 → 76 → 9 → 26 → 1 出力 24 説明 considering alternate strings
-
C++で指定された数字で形成できる最大の数を見つけます
数字の配列があるとします。配列のすべての桁を使用して取得できる最大数を見つける必要があります。したがって、配列が[3、3、9、6、2、5]のような場合、最大数は965332になります。 この問題から、数字を昇順ではなく簡単に並べ替えてから印刷できることがわかります。しかし、より効率的な方法でこれを解決できます。サイズ10の配列を1つ作成して各桁の頻度を格納し、それに応じて9から0までの数値を出力できます。 例 #include <iostream> #include <string> using namespace std; int maxNumFromNum(int