跳转至

数组与链表

📖 章节简介

本章将介绍C++的数组和链表数据结构,包括数组操作、链表实现和双向链表。

数组与链表对比图

上图对比了数组与链表在内存布局、访问方式以及插入删除复杂度上的差异。

📊 数组

1. 基本数组操作

C++
// 基本数组操作
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    // 数组声明和初始化
    int arr[] = {5, 2, 8, 1, 9, 3, 7, 4, 6, 0};
    int size = sizeof(arr) / sizeof(arr[0]);

    // 遍历数组
    cout << "原始数组:" << endl;
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    // 数组排序
    sort(arr, arr + size);
    cout << "\n排序后:" << endl;
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    // 查找元素
    int target = 7;
    bool found = false;
    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            cout << "\n找到" << target << "在位置" << i << endl;
            found = true;
            break;
        }
    }

    if (!found) {
        cout << "\n未找到" << target << endl;
    }

    // 数组反转
    reverse(arr, arr + size);
    cout << "\n反转后:" << endl;
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    return 0;
}

2. 动态数组

C++
// 动态数组
#include <iostream>
using namespace std;

class DynamicArray {
private:
    int* data;
    int size;
    int capacity;

public:
    DynamicArray(int initialCapacity = 10) {
        capacity = initialCapacity;
        size = 0;
        data = new int[capacity];
    }

    ~DynamicArray() {
        delete[] data;
    }

    // 禁用拷贝(防止双重释放)
    DynamicArray(const DynamicArray&) = delete;
    DynamicArray& operator=(const DynamicArray&) = delete;

    void add(int value) {
        if (size >= capacity) {
            resize();
        }
        data[size++] = value;
    }

    int get(int index) {
        if (index < 0 || index >= size) {
            cout << "索引越界!" << endl;
            return -1;
        }
        return data[index];
    }

    void remove(int index) {
        if (index < 0 || index >= size) {
            cout << "索引越界!" << endl;
            return;
        }

        for (int i = index; i < size - 1; i++) {
            data[i] = data[i + 1];
        }
        size--;
    }

    int getSize() const {
        return size;
    }

private:
    // 扩容策略:容量翻倍,均摊插入时间复杂度为O(1)
    void resize() {
        int newCapacity = capacity * 2;
        int* newData = new int[newCapacity];

        // 将旧数据拷贝到新数组
        for (int i = 0; i < size; i++) {
            newData[i] = data[i];
        }

        delete[] data; // 释放旧内存
        data = newData;
        capacity = newCapacity;
    }
};

int main() {
    DynamicArray arr;

    // 添加元素
    for (int i = 1; i <= 15; i++) {
        arr.add(i);
    }

    // 遍历数组
    cout << "数组元素:" << endl;
    for (int i = 0; i < arr.getSize(); i++) {
        cout << arr.get(i) << " ";
    }
    cout << endl;
    cout << "数组大小: " << arr.getSize() << endl;

    // 删除元素
    arr.remove(5);
    cout << "\n删除第5个元素后:" << endl;
    for (int i = 0; i < arr.getSize(); i++) {
        cout << arr.get(i) << " ";
    }
    cout << endl;

    return 0;
}

🔗 链表

1. 单链表

C++
// 单链表
#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* next;

    Node(int val) : data(val), next(nullptr) {}
};

class LinkedList {
private:
    Node* head;

public:
    LinkedList() : head(nullptr) {}

    ~LinkedList() {
        Node* current = head;
        while (current != nullptr) {
            Node* next = current->next;
            delete current;
            current = next;
        }
    }

    void add(int value) {
        Node* newNode = new Node(value);
        newNode->next = head;
        head = newNode;
    }

    void remove(int value) {
        Node* current = head;
        Node* prev = nullptr; // 记录前驱节点,用于跳过被删节点

        while (current != nullptr) {
            if (current->data == value) {
                if (prev == nullptr) {
                    head = current->next; // 删除的是头节点,更新head
                } else {
                    prev->next = current->next; // 前驱跳过当前节点,断开链接
                }
                delete current;
                return;
            }
            prev = current;
            current = current->next;
        }
    }

    bool contains(int value) {
        Node* current = head;
        while (current != nullptr) {
            if (current->data == value) {
                return true;
            }
            current = current->next;
        }
        return false;
    }

    void display() {
        Node* current = head;
        while (current != nullptr) {
            cout << current->data << " -> ";
            current = current->next;
        }
        cout << "nullptr" << endl;
    }
};

int main() {
    LinkedList list;

    // 添加元素
    list.add(10);
    list.add(20);
    list.add(30);
    list.add(40);

    // 显示链表
    cout << "链表元素:" << endl;
    list.display();

    // 查找元素
    cout << "\n包含20: " << list.contains(20) << endl;
    cout << "包含50: " << list.contains(50) << endl;

    // 删除元素
    list.remove(20);
    cout << "\n删除20后:" << endl;
    list.display();

    return 0;
}

2. 双向链表

C++
// 双向链表
#include <iostream>
using namespace std;

struct DoublyNode {
    int data;
    DoublyNode* prev;
    DoublyNode* next;

    DoublyNode(int val) : data(val), prev(nullptr), next(nullptr) {}
};

class DoublyLinkedList {
private:
    DoublyNode* head;
    DoublyNode* tail;

public:
    DoublyLinkedList() : head(nullptr), tail(nullptr) {}

    ~DoublyLinkedList() {
        DoublyNode* current = head;
        while (current != nullptr) {
            DoublyNode* next = current->next;
            delete current;
            current = next;
        }
    }

    void add(int value) {
        DoublyNode* newNode = new DoublyNode(value);

        if (head == nullptr) {
            head = tail = newNode;
        } else {
            tail->next = newNode;
            newNode->prev = tail;
            tail = newNode;
        }
    }

    void remove(int value) {
        DoublyNode* current = head;

        while (current != nullptr) {
            if (current->data == value) {
                // 处理前向指针:若为头节点则更新head,否则前驱跳过当前节点
                if (current->prev == nullptr) {
                    head = current->next;
                } else {
                    current->prev->next = current->next;
                }

                // 处理后向指针:若为尾节点则更新tail,否则后继跳过当前节点
                if (current->next != nullptr) {
                    current->next->prev = current->prev;
                } else {
                    tail = current->prev;
                }

                delete current;
                return;
            }
            current = current->next;
        }
    }

    void displayForward() {
        DoublyNode* current = head;
        while (current != nullptr) {
            cout << current->data << " <-> ";
            current = current->next;
        }
        cout << "nullptr" << endl;
    }

    void displayBackward() {
        DoublyNode* current = tail;
        while (current != nullptr) {
            cout << current->data << " <-> ";
            current = current->prev;
        }
        cout << "nullptr" << endl;
    }
};

int main() {
    DoublyLinkedList list;

    // 添加元素
    list.add(10);
    list.add(20);
    list.add(30);
    list.add(40);

    // 正向遍历
    cout << "正向遍历:" << endl;
    list.displayForward();

    // 反向遍历
    cout << "\n反向遍历:" << endl;
    list.displayBackward();

    // 删除元素
    list.remove(20);
    cout << "\n删除20后:" << endl;
    list.displayForward();

    return 0;
}

💡 最佳实践

1. 内存管理

C++
// 内存管理
#include <memory>

int main() {
    // ✅ 好的做法:使用智能指针
    std::unique_ptr<int> ptr = std::make_unique<int>(10);  // unique_ptr 独占式智能指针,自动释放内存

    // ❌ 不好的做法:忘记释放内存
    int* rawPtr = new int(10);
    // delete rawPtr;  // 容易忘记

    return 0;
}

2. 性能优化

C++
// 性能优化
int main() {
    // ✅ 好的做法:预分配内存
    const int SIZE = 1000;
    int* arr = new int[SIZE];

    // ❌ 不好的做法:频繁重新分配
    int* dynamicArr = new int[10];
    // ... 频繁重新分配 ...

    delete[] arr;
    delete[] dynamicArr;

    return 0;
}

📝 练习题

基础题

  1. 数组和链表有什么区别?
  2. 如何实现动态数组?
  3. 如何实现单链表?

进阶题

  1. 实现双向链表。
  2. 实现循环链表。
  3. 优化链表性能。

实践题

  1. 创建一个栈数据结构。
  2. 实现一个队列数据结构。
  3. 构建一个简单的内存管理器。

📚 推荐阅读

🔗 下一章

栈与队列 - 学习C++的栈和队列。