数组:最基础也最常用
数组是大多数人学编程最早接触的数据结构。它就像一排整齐的储物柜,每个位置都有固定编号,通过下标能快速找到对应元素。比如你在写一个成绩管理系统,用数组存100个学生的分数,访问第5个学生就直接 scores[4](别忘了下标从0开始)。
虽然插入删除不方便,但查询效率高,适合频繁读取的场景。
int arr[5] = {10, 20, 30, 40, 50};
arr[2] = 35; // 修改第三个元素链表:灵活的动态结构
链表像是一串钥匙环,每把钥匙挂着数据和下一个钥匙的位置。不像数组需要连续内存,链表可以零散分布,增删节点时只需改指针,特别适合不确定数据量的场景。
比如你做一个播放列表,用户随时添加或删除歌曲,用链表就比数组更高效。
struct Node {
int data;
struct Node* next;
};
// 创建新节点
struct Node* head = NULL;
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = 100;
newNode->next = head;
head = newNode;栈:后进先出的典型
栈就像一摞盘子,只能从顶部拿或放。浏览器的“返回”功能就是典型的栈应用——你点进一个网页压入栈,点“返回”就弹出上一个页面。
实现起来很简单,可以用数组或链表,关键只允许在一端操作。
#define MAX 100
int stack[MAX];
int top = -1;
void push(int item) {
if (top < MAX-1) {
stack[++top] = item;
}
}
int pop() {
if (top >= 0) {
return stack[top--];
}
return -1;
}队列:排队处理的模型
队列讲究先来后到,像食堂打饭窗口。任务调度、消息系统都靠它维持秩序。比如你发了个打印任务,系统把它放进队列,等前面的打完才轮到你。
通常用循环数组或链表实现,避免空间浪费。
struct Queue {
int items[100];
int front;
int rear;
};
void enqueue(struct Queue* q, int value) {
q->rear++;
q->items[q->rear] = value;
}哈希表:查找快得飞起
你想快速查手机号,总不能一个个翻通讯录吧?哈希表就是你的智能索引。它通过哈希函数把键(比如姓名)转成地址,实现接近O(1)的查询速度。
当然会有冲突,常见的解决办法是链地址法——同一个地址挂个链表存多个值。
#include <stdlib.h>
#include <string.h>
#define SIZE 100
struct Entry {
char* key;
char* value;
struct Entry* next;
};
struct Entry* hashTable[SIZE];二叉树:分层管理的智慧
公司组织架构图就是一棵树。二叉树每个节点最多两个孩子,特别适合做搜索。二叉搜索树还规定左小右大,查起来很快。
比如你写个词典程序,单词按字母顺序存进树里,查找效率远超线性扫描。
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* insert(struct TreeNode* root, int value) {
if (root == NULL) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = value;
node->left = node->right = NULL;
return node;
}
if (value < root->val)
root->left = insert(root->left, value);
else
root->right = insert(root->right, value);
return root;
}