我已经知道,如果链表中的数字是质数节点,则可以打印出来,并输出输出,但是不确定如何构造代码,因此它是一维动态数组并实现MergeSort功能,以便将其输出为升序。感谢您的帮助,谢谢!
using namespace std;
struct Node {
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;
}
bool isPrime(int n) {
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
int countPrime(Node **head_ref) {
int count = 0;
Node *ptr = *head_ref;
while (ptr != NULL) {
// If current node is prime
if (isPrime(ptr->data)) {
// Update count
count++;
}
ptr = ptr->next;
}
return count;
}
int main() {
Node *head = NULL;
push(&head, 17);
push(&head, 10);
push(&head, 6);
push(&head, 5);
push(&head, 15);
cout << "Count of prime nodes = " << countPrime(&head);
return 0;
}