이 튜토리얼에서는 단일 연결 리스트에서 모든 프라임 노드를 삭제하는 방법을 배울 것입니다.
문제를 해결하는 단계를 살펴보겠습니다.
-
데이터와 다음 포인터로 구조체를 작성하십시오.
-
단일 연결 리스트에 노드를 삽입하는 함수를 작성하십시오.
-
더미 데이터로 단일 연결 리스트를 초기화합니다.
-
단일 연결 목록을 반복합니다. 현재 노드 데이터가 소수인지 여부를 찾습니다.
-
현재 데이터가 소수가 아니면 노드를 삭제합니다.
-
노드를 삭제하는 함수를 작성하십시오. 노드를 삭제할 때 다음 세 가지 경우를 고려하십시오.
-
노드가 헤드 노드인 경우 헤드를 다음 노드로 이동합니다.
-
노드가 중간 노드인 경우 다음 노드를 이전 노드에 연결
-
노드가 끝 노드인 경우 이전 노드 링크를 제거합니다.
-
예시
코드를 봅시다.
#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 ->
결론
튜토리얼에서 질문이 있는 경우 댓글 섹션에 언급하세요.