이 튜토리얼에서는 이중 연결 리스트에서 주어진 위치의 노드를 삭제하는 방법을 배울 것입니다.
문제를 해결하는 단계를 살펴보겠습니다.
-
데이터, 이전 및 다음 포인터로 구조체를 작성합니다.
-
이중 연결 리스트에 노드를 삽입하는 함수를 작성하십시오.
-
더미 데이터로 이중 연결 리스트를 초기화합니다.
-
노드를 삭제할 위치를 초기화합니다.
-
연결 리스트를 반복하고 노드를 삭제하기 위해 주어진 위치의 노드를 찾습니다.
-
노드를 삭제하는 함수를 작성하십시오. 노드를 삭제할 때 다음 세 가지 경우를 고려하십시오.
-
노드가 헤드 노드인 경우 헤드를 다음 노드로 이동합니다.
-
노드가 중간 노드인 경우 다음 노드를 이전 노드에 연결
-
노드가 끝 노드인 경우 이전 노드 링크를 제거합니다.
-
예시
코드를 봅시다.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *prev, *next;
};
void deleteNode(struct Node** head_ref, struct Node* del) {
if (*head_ref == NULL || del == NULL) {
return;
}
// head node
if (*head_ref == del) {
*head_ref = del->next;
}
// middle node
if (del->next != NULL) {
del->next->prev = del->prev;
}
// end node
if (del->prev != NULL) {
del->prev->next = del->next;
}
free(del);
}
void deleteNodeAtGivenPosition(struct Node** head_ref, int n) {
if (*head_ref == NULL || n <= 0) {
return;
}
struct Node* current = *head_ref;
int i;
for (int i = 1; current != NULL && i < n; i++) {
current = current->next;
}
if (current == NULL) {
return;
}
deleteNode(head_ref, current);
}
void insertNode(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct 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;
}
void printLinkedList(struct Node* head) {
while (head != NULL) {
cout << head->data << "->";
head = head->next;
}
}
int main() {
struct Node* head = NULL;
insertNode(&head, 5);
insertNode(&head, 2);
insertNode(&head, 4);
insertNode(&head, 8);
insertNode(&head, 10);
cout << "Doubly linked list before deletion" << endl;
printLinkedList(head);
int n = 2;
deleteNodeAtGivenPosition(&head, n);
cout << "\nDoubly linked list after deletion" << endl;
printLinkedList(head);
return 0;
} 출력
위의 프로그램을 실행하면 다음과 같은 결과를 얻을 수 있습니다.
Doubly linked list before deletion 10->8->4->2->5-> Doubly linked list after deletion 10->4->2->5->
결론
튜토리얼에서 질문이 있는 경우 댓글 섹션에 언급하세요.