C++單鏈表中刪除所有非素數節點
在本教程中,我們將學習如何從單鏈表中刪除所有素數節點。
讓我們看看解決問題的步驟。
編寫包含資料和下一個指標的結構體。
編寫一個函式將節點插入到單鏈表中。
用虛擬資料初始化單鏈表。
遍歷單鏈表。查詢當前節點資料是否為素數。
如果當前資料不是素數,則刪除該節點。
編寫一個刪除節點的函式。刪除節點時,請考慮以下三種情況。
如果節點是頭節點,則將頭節點移動到下一個節點。
如果節點是中間節點,則將下一個節點連結到前一個節點。
如果節點是尾節點,則刪除前一個節點的連結。
示例
讓我們看看程式碼。
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
void insertNode(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) {
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;
}
void deleteNonPrimeNodes(Node** head_ref) {
Node* ptr = *head_ref;
while (ptr != NULL && !isPrime(ptr->data)) {
Node *temp = ptr;
ptr = ptr->next;
delete(temp);
}
*head_ref = ptr;
if (ptr == NULL) {
return;
}
Node *curr = ptr->next;
while (curr != NULL) {
if (!isPrime(curr->data)) {
ptr->next = curr->next;
delete(curr);
curr = ptr->next;
}
else {
ptr = curr;
curr = curr->next;
}
}
}
void printLinkedList(Node* head) {
while (head != NULL) {
cout << head->data << " -> ";
head = head->next;
}
}
int main() {
Node* head = NULL;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
insertNode(&head, 4);
insertNode(&head, 5);
insertNode(&head, 6);
cout << "Linked List before deletion:" << endl;
printLinkedList(head);
deleteNonPrimeNodes(&head);
cout << "\nLinked List after deletion:" << endl;
printLinkedList(head);
}輸出
如果執行以上程式碼,則會得到以下結果。
Linked List before deletion: 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> Linked List after deletion: 5 -> 3 -> 2 ->
結論
如果您對本教程有任何疑問,請在評論部分提出。
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP