ในปัญหานี้ เราได้รับรายการเชื่อมโยง งานของเราคือสร้างฟังก์ชันที่สามารถนับจำนวนครั้งที่ตัวเลขที่ระบุเกิดขึ้นในรายการที่เชื่อมโยงได้
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
อินพุต
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