이 튜토리얼에서는 N M 이후의 노드 연결 목록의 노드.
문제를 해결하는 단계를 살펴보겠습니다.
-
연결 목록 노드에 대한 구조체 노드를 작성하십시오.
-
더미 데이터로 연결 리스트를 초기화합니다.
-
M노드 이후에 N노드를 삭제하는 함수를 작성하세요.
-
헤드 포인터로 포인터를 초기화합니다.
-
연결 목록의 끝까지 반복합니다.
-
M 노드가 될 때까지 포인터를 다음 노드로 이동합니다.
-
N개의 노드 삭제
-
포인터를 다음 노드로 이동
-
-
연결 목록 인쇄
예시
코드를 봅시다.
#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;
}
void printLinkedList(Node *head) {
Node *temp = head;
while (temp != NULL) {
cout<< temp->data << " -> ";
temp = temp->next;
}
cout << "Null" << endl;
}
void deleteNNodesAfterMNodes(Node *head, int M, int N) {
Node *current = head, *temp;
int count;
while (current) {
// skip M nodes
for (count = 1; count < M && current!= NULL; count++) {
current = current->next;
}
// end of the linked list
if (current == NULL) {
return;
}
// deleting N nodes after M nodes
temp = current->next;
for (count = 1; count <= N && temp != NULL; count++) {
Node *deletingNode = temp;
temp = temp->next;
free(deletingNode);
}
current->next = temp;
current = temp;
}
}
int main() {
Node* head = NULL;
int M = 1, N = 2;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
insertNode(&head, 4);
insertNode(&head, 5);
insertNode(&head, 6);
insertNode(&head, 7);
insertNode(&head, 8);
insertNode(&head, 9);
cout << "Linked list before deletion: ";
printLinkedList(head);
deleteNNodesAfterMNodes(head, M, N);
cout << "Linked list after deletion: ";
printLinkedList(head);
return 0;
} 출력
위의 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.
Linked list before deletion: 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> Null Linked list after deletion: 9 -> 6 -> 3 -> Null
결론
튜토리얼에서 질문이 있는 경우 댓글 섹션에 언급하세요.