c++ example如何展示數(shù)據(jù)結(jié)構(gòu)與算法

c++
小樊
81
2024-09-27 18:10:46
欄目: 編程語言

在C++中,我們可以通過多種方式展示數(shù)據(jù)結(jié)構(gòu)與算法的結(jié)合。以下是一個(gè)簡(jiǎn)單的例子,使用鏈表(一種常見的數(shù)據(jù)結(jié)構(gòu))和排序算法(如冒泡排序)來展示它們是如何協(xié)同工作的。

首先,我們定義一個(gè)鏈表節(jié)點(diǎn)結(jié)構(gòu)體和一個(gè)簡(jiǎn)單的鏈表類:

#include <iostream>
using namespace std;

// 鏈表節(jié)點(diǎn)結(jié)構(gòu)體
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};

// 鏈表類
class LinkedList {
public:
    LinkedList() : head(NULL) {}

    // 在鏈表末尾添加一個(gè)新節(jié)點(diǎn)
    void append(int val) {
        if (!head) {
            head = new ListNode(val);
            return;
        }
        ListNode* current = head;
        while (current->next) {
            current = current->next;
        }
        current->next = new ListNode(val);
    }

    // 打印鏈表
    void print() {
        ListNode* current = head;
        while (current) {
            cout << current->val << " ";
            current = current->next;
        }
        cout << endl;
    }

private:
    ListNode* head;
};

接下來,我們實(shí)現(xiàn)一個(gè)簡(jiǎn)單的冒泡排序算法,并將其應(yīng)用于鏈表:

// 冒泡排序算法
void bubbleSort(LinkedList& list) {
    if (!list.head || !list.head->next) {
        return;
    }

    bool swapped;
    ListNode* current = list.head;
    ListNode* next;

    do {
        swapped = false;
        current = list.head;

        while (current->next) {
            if (current->val > current->next->val) {
                // 交換兩個(gè)節(jié)點(diǎn)的值
                int temp = current->val;
                current->val = current->next->val;
                current->next->val = temp;
                swapped = true;
            }
            current = current->next;
        }
    } while (swapped);
}

最后,我們創(chuàng)建一個(gè)鏈表實(shí)例,向其中添加一些元素,并使用冒泡排序?qū)ζ溥M(jìn)行排序:

int main() {
    LinkedList list;
    list.append(5);
    list.append(3);
    list.append(8);
    list.append(1);
    list.append(4);

    cout << "原始鏈表: ";
    list.print();

    bubbleSort(list);

    cout << "排序后的鏈表: ";
    list.print();

    return 0;
}

這個(gè)例子展示了如何使用鏈表作為數(shù)據(jù)結(jié)構(gòu),以及如何使用冒泡排序算法對(duì)其進(jìn)行排序。當(dāng)然,這只是一個(gè)簡(jiǎn)單的示例,實(shí)際應(yīng)用中可能會(huì)涉及更復(fù)雜的數(shù)據(jù)結(jié)構(gòu)和算法。

0