Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Chương trình C++ triển khai danh sách liên kết đơn (Singly Linked List)


Danh sách liên kết đơn (Singly Linked List): mỗi nút chứa dữ liệu và con trỏ next. Chỉ cần head để truy cập. Nút cuối trỏ next = NULL.

Ví dụ

#include <iostream>
using namespace std;

struct Node {
    int data;
    struct Node *next;
};

struct Node* head = NULL;

void insert(int new_data) {
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = head;
    head = new_node;
}

void display() {
    struct Node* ptr;
    ptr = head;
    while (ptr != NULL) {
        cout << ptr->data << " ";
        ptr = ptr->next;
    }
}

int main() {
    insert(3);
    insert(1);
    insert(7);
    insert(2);
    insert(9);
    cout << "The linked list is: ";
    display();
    return 0;
}

Kết quả

The linked list is: 9 2 7 1 3

Cấu trúc Node

struct Node {
    int data;
    struct Node *next;
};

Hàm insert() - Thêm vào đầu

Tạo new_node, gán dữ liệu, next = head, cập nhật head = new_node.

void insert(int new_data) {
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = head;
    head = new_node;
}

Hàm display() - Hiển thị

Duyệt từ head theo next cho đến NULL.

void display() {
    struct Node* ptr;
    ptr = head;
    while (ptr != NULL) {
        cout << ptr->data << " ";
        ptr = ptr->next;
    }
}

Hàm main()

int main() {
    insert(3);
    insert(1);
    insert(7);
    insert(2);
    insert(9);
    cout << "The linked list is: ";
    display();
    return 0;
}