引言在C语言编程中,数据的存储和遍历是基础且关键的部分。理解如何高效地遍历存储的数据结构对于编写高性能的程序至关重要。本文将深入探讨C语言中几种常见的数据结构及其遍历技巧,帮助读者轻松掌握高效数据遍历...
在C语言编程中,数据的存储和遍历是基础且关键的部分。理解如何高效地遍历存储的数据结构对于编写高性能的程序至关重要。本文将深入探讨C语言中几种常见的数据结构及其遍历技巧,帮助读者轻松掌握高效数据遍历的秘密。
数组的遍历是最基础的,通常使用循环结构来实现。
#include
int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); return 0;
} 在C++中,向量是一种动态数组,C11引入了C风格的向量。向量的遍历可以使用range-based for循环。
#include
#include
int main() { std::vector v = {1, 2, 3, 4, 5}; for (auto &i : v) { std::cout << i << " "; } std::cout << std::endl; return 0;
} 图的遍历分为深度优先搜索(DFS)和广度优先搜索(BFS)。
#include
#include
#define MAXVEX 20
#define INFINITY 65535
typedef struct { int vexs[MAXVEX]; int arc[MAXVEX][MAXVEX]; int numVertexes, numEdges;
} MGraph;
void DFS(MGraph G, int v) { int visited[MAXVEX] = {0}; visited[v] = 1; printf("%d ", v); for (int i = 0; i < G.numVertexes; i++) { if (G.arc[v][i] != INFINITY && !visited[i]) { DFS(G, i); } }
}
int main() { MGraph G; // 初始化图G // ... DFS(G, 0); return 0;
} #include
#include
#define MAXVEX 20
#define INFINITY 65535
typedef struct { int vexs[MAXVEX]; int arc[MAXVEX][MAXVEX]; int numVertexes, numEdges;
} MGraph;
void BFS(MGraph G, int v) { int visited[MAXVEX] = {0}; int queue[MAXVEX]; int front = 0, rear = 0; visited[v] = 1; queue[rear++] = v; while (front != rear) { int w = queue[front++]; printf("%d ", w); for (int i = 0; i < G.numVertexes; i++) { if (G.arc[w][i] != INFINITY && !visited[i]) { visited[i] = 1; queue[rear++] = i; } } }
}
int main() { MGraph G; // 初始化图G // ... BFS(G, 0); return 0;
} 树的遍历包括前序遍历、中序遍历和后序遍历。
#include
#include
typedef struct TreeNode { int data; struct TreeNode *left; struct TreeNode *right;
} TreeNode;
void PreOrderTraversal(TreeNode *T) { if (T != NULL) { printf("%d ", T->data); PreOrderTraversal(T->left); PreOrderTraversal(T->right); }
}
int main() { TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode)); // 构建树 // ... PreOrderTraversal(root); return 0;
} void InOrderTraversal(TreeNode *T) { if (T != NULL) { InOrderTraversal(T->left); printf("%d ", T->data); InOrderTraversal(T->right); }
}void PostOrderTraversal(TreeNode *T) { if (T != NULL) { PostOrderTraversal(T->left); PostOrderTraversal(T->right); printf("%d ", T->data); }
}通过本文的介绍,读者应该能够掌握C语言中几种常见数据结构的遍历技巧。这些技巧在编写高效程序时非常有用,特别是在处理大量数据时。掌握这些遍历方法将为编写更优化的代码打下坚实的基础。