이 튜토리얼에서는 이중 연결 리스트(Doubly Linked List)에서 데이터 값이 소수인 노드를 모두 찾아 삭제하는 방법을 알아보겠습니다.
문제 해결 접근 방식
문제를 해결하기 위한 전체적인 흐름은 다음과 같습니다.
- 데이터(data)와 prev, next 포인터를 가지는 구조체(struct)를 정의합니다.
- 이중 연결 리스트에 새 노드를 삽입하는 함수를 작성합니다.
- 테스트용 더미 데이터로 이중 연결 리스트를 초기화합니다.
- 리스트를 순회하면서 현재 노드의 데이터가 소수인지 판별합니다.
- 현재 데이터가 소수라면 해당 노드를 삭제합니다.
노드 삭제 시 고려해야 할 세 가지 경우
노드를 삭제하는 함수를 작성할 때는 아래의 세 가지 상황을 반드시 처리해야 합니다.
- 삭제할 노드가 헤드(head) 노드인 경우: 헤드 포인터를 다음 노드로 이동시킵니다.
- 삭제할 노드가 중간 노드인 경우: 다음 노드와 이전 노드를 서로 연결하여 리스트를 유지합니다.
- 삭제할 노드가 마지막 노드인 경우: 이전 노드의 next 링크를 제거합니다.
예제 코드
위 내용을 바탕으로 작성한 전체 코드는 다음과 같습니다.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *prev, *next;
};
void insertNode(Node** head_ref, int new_data) {
Node* new_node = (Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->prev = NULL;
new_node->next = (*head_ref);
if ((*head_ref) != NULL) {
(*head_ref)->prev = new_node;
}
(*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 deleteNode(Node** head_ref, Node* del) {
if (*head_ref == NULL || del == NULL) {
return;
}
if (*head_ref == del) {
*head_ref = del->next;
}
if (del->next != NULL) {
del->next->prev = del->prev;
}
if (del->prev != NULL) {
del->prev->next = del->next;
}
free(del);
return;
}
void deletePrimeNodes(Node** head_ref) {
Node* temp = *head_ref;
Node* next;
while (temp != NULL) {
next = temp->next;
if (isPrime(temp->data)) {
deleteNode(head_ref, temp);
}
temp = 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);
deletePrimeNodes(&head);
cout << "\nLinked List after deletion:" << endl;
printLinkedList(head);
}실행 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
Linked List before deletion: 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> Linked List after deletion: 6 -> 4 -> 1 ->
핵심 포인트 정리
- 소수 판별 함수(isPrime): 2와 3으로 나누어 떨어지는지 먼저 확인하고, 이후에는 6k ± 1 형태의 수만 검사하는 최적화된 방식을 사용합니다. 시간 복잡도는 O(√n)입니다.
- 안전한 순회: 노드를 삭제하기 전에 반드시 다음 노드의 주소를 미리 저장해 두어야 순회가 끊기지 않습니다.
- 포인터 정리: 삭제 후에는 free()를 호출하여 메모리 누수를 방지해야 합니다.
마무리
이번 튜토리얼에서는 이중 연결 리스트를 순회하며 소수 값을 가진 노드를 안전하게 삭제하는 방법을 배웠습니다. 헤드 노드, 중간 노드, 마지막 노드의 세 가지 경우를 꼼꼼히 처리하는 것이 핵심입니다. 튜토리얼에 대해 궁금한 점이 있다면 댓글로 남겨주세요.