c++

c++ example如何展示数据结构与算法

小樊
81
2024-09-27 18:10:46
栏目: 编程语言

在C++中,我们可以通过多种方式展示数据结构与算法的结合。以下是一个简单的例子,使用链表(一种常见的数据结构)和排序算法(如冒泡排序)来展示它们是如何协同工作的。

首先,我们定义一个链表节点结构体和一个简单的链表类:

#include <iostream>
using namespace std;

// 链表节点结构体
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};

// 链表类
class LinkedList {
public:
    LinkedList() : head(NULL) {}

    // 在链表末尾添加一个新节点
    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;
};

接下来,我们实现一个简单的冒泡排序算法,并将其应用于链表:

// 冒泡排序算法
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) {
                // 交换两个节点的值
                int temp = current->val;
                current->val = current->next->val;
                current->next->val = temp;
                swapped = true;
            }
            current = current->next;
        }
    } while (swapped);
}

最后,我们创建一个链表实例,向其中添加一些元素,并使用冒泡排序对其进行排序:

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;
}

这个例子展示了如何使用链表作为数据结构,以及如何使用冒泡排序算法对其进行排序。当然,这只是一个简单的示例,实际应用中可能会涉及更复杂的数据结构和算法。

0
看了该问题的人还看了