Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

สร้าง Linked List จากอาร์เรย์ใน C++


ในบทช่วยสอนนี้ เราจะเรียนรู้วิธีสร้าง Linked List จากอาร์เรย์ที่กำหนด

ขั้นตอนการแก้ปัญหา

  1. กำหนดค่าอาร์เรย์ตัวอย่าง
  2. เขียนโครงสร้างโหนด (struct Node)
  3. วนลูปผ่านอาร์เรย์:
    • สร้างโหนดใหม่พร้อมข้อมูล
    • แทรกโหนดใหม่เข้า Linked List
  4. พิมพ์ Linked List

โค้ดตัวอย่าง

#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

สรุป

โค้ดนี้สาธิตการสร้าง Singly Linked List จากอาร์เรย์โดยการแทรกที่ท้าย (append) หากมีข้อสงสัย สามารถถามได้ในส่วนความคิดเห็น