이 튜토리얼에서는 주어진 배열에서 연결 리스트를 만드는 방법을 배울 것입니다.
문제를 해결하는 단계를 살펴보겠습니다.
-
더미 데이터로 어레이를 초기화합니다.
-
구조체 노드를 작성합니다.
-
배열을 반복합니다.
-
데이터로 새 노드를 만듭니다.
-
새 노드를 연결 목록에 삽입합니다.
-
-
연결 목록을 인쇄합니다.
예
코드를 봅시다.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
struct Node* newNode(int data) {
Node* node = new Node;
node->data = data;
node->next = NULL;
return node;
}
void insertNewNode(Node** root, int data) {
Node* node = newNode(data);
Node* ptr;
if (*root == NULL) {
*root = node;
}
else {
ptr = *root;
while (ptr->next != NULL) {
ptr = ptr->next;
}
ptr->next = node;
}
}
void printLinkedList(Node* root) {
while (root != NULL) {
cout << root->data << " -> ";
root = root->next;
}
cout << "NULL" << endl;
}
Node* createLinkedList(int arr[], int n) {
Node *root = NULL;
for (int i = 0; i < n; i++) {
insertNewNode(&root, arr[i]);
}
return root;
}
int main() {
int arr[] = { 1, 2, 3, 4, 5 }, n = 5;
Node* root = createLinkedList(arr, n);
printLinkedList(root);
return 0;
} 출력
위의 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.
1 -> 2 -> 3 -> 4 -> 5 -> NULL
결론
튜토리얼에서 질문이 있는 경우 댓글 섹션에 언급하세요.