Simplify struct declarations of C.

Use PascalCase for all structs in C.
SImplify n_queens.c
Format C code for chapter of graph.
This commit is contained in:
krahets
2023-10-18 02:16:26 +08:00
parent 070d23ee6e
commit 1e49574332
35 changed files with 503 additions and 599 deletions

View File

@ -7,20 +7,18 @@
#include "../utils/common.h"
/* 列表类简易实现 */
struct myList {
typedef struct {
int *arr; // 数组(存储列表元素)
int capacity; // 列表容量
int size; // 列表大小
int extendRatio; // 列表每次扩容的倍数
};
} MyList;
typedef struct myList myList;
void extendCapacity(myList *nums);
void extendCapacity(MyList *nums);
/* 构造函数 */
myList *newMyList() {
myList *nums = malloc(sizeof(myList));
MyList *newMyList() {
MyList *nums = malloc(sizeof(MyList));
nums->capacity = 10;
nums->arr = malloc(sizeof(int) * nums->capacity);
nums->size = 0;
@ -29,35 +27,35 @@ myList *newMyList() {
}
/* 析构函数 */
void delMyList(myList *nums) {
void delMyList(MyList *nums) {
free(nums->arr);
free(nums);
}
/* 获取列表长度 */
int size(myList *nums) {
int size(MyList *nums) {
return nums->size;
}
/* 获取列表容量 */
int capacity(myList *nums) {
int capacity(MyList *nums) {
return nums->capacity;
}
/* 访问元素 */
int get(myList *nums, int index) {
int get(MyList *nums, int index) {
assert(index >= 0 && index < nums->size);
return nums->arr[index];
}
/* 更新元素 */
void set(myList *nums, int index, int num) {
void set(MyList *nums, int index, int num) {
assert(index >= 0 && index < nums->size);
nums->arr[index] = num;
}
/* 尾部添加元素 */
void add(myList *nums, int num) {
void add(MyList *nums, int num) {
if (size(nums) == capacity(nums)) {
extendCapacity(nums); // 扩容
}
@ -66,7 +64,7 @@ void add(myList *nums, int num) {
}
/* 中间插入元素 */
void insert(myList *nums, int index, int num) {
void insert(MyList *nums, int index, int num) {
assert(index >= 0 && index < size(nums));
// 元素数量超出容量时,触发扩容机制
if (size(nums) == capacity(nums)) {
@ -81,7 +79,7 @@ void insert(myList *nums, int index, int num) {
/* 删除元素 */
// 注意stdio.h 占用了 remove 关键词
int removeNum(myList *nums, int index) {
int removeNum(MyList *nums, int index) {
assert(index >= 0 && index < size(nums));
int num = nums->arr[index];
for (int i = index; i < size(nums) - 1; i++) {
@ -92,7 +90,7 @@ int removeNum(myList *nums, int index) {
}
/* 列表扩容 */
void extendCapacity(myList *nums) {
void extendCapacity(MyList *nums) {
// 先分配空间
int newCapacity = capacity(nums) * nums->extendRatio;
int *extend = (int *)malloc(sizeof(int) * newCapacity);
@ -111,14 +109,14 @@ void extendCapacity(myList *nums) {
}
/* 将列表转换为 Array 用于打印 */
int *toArray(myList *nums) {
int *toArray(MyList *nums) {
return nums->arr;
}
/* Driver Code */
int main() {
/* 初始化列表 */
myList *nums = newMyList();
MyList *nums = newMyList();
/* 尾部添加元素 */
add(nums, 1);
add(nums, 3);

View File

@ -9,25 +9,17 @@
#define MAX_N 100
#define MAX_RES 1000
/* 放置结果 */
struct result {
char ***data;
int size;
};
typedef struct result Result;
/* 回溯算法N 皇后 */
void backtrack(int row, int n, char state[MAX_N][MAX_N], Result *res,
bool cols[MAX_N], bool diags1[2 * MAX_N - 1], bool diags2[2 * MAX_N - 1]) {
void backtrack(int row, int n, char state[MAX_N][MAX_N], char ***res, int *resSize, bool cols[MAX_N],
bool diags1[2 * MAX_N - 1], bool diags2[2 * MAX_N - 1]) {
// 当放置完所有行时,记录解
if (row == n) {
res->data[res->size] = (char **)malloc(sizeof(char *) * n);
res[*resSize] = (char **)malloc(sizeof(char *) * n);
for (int i = 0; i < n; ++i) {
res->data[res->size][i] = (char *)malloc(sizeof(char) * (n + 1));
strcpy(res->data[res->size][i], state[i]);
res[*resSize][i] = (char *)malloc(sizeof(char) * (n + 1));
strcpy(res[*resSize][i], state[i]);
}
res->size++;
(*resSize)++;
return;
}
// 遍历所有列
@ -41,7 +33,7 @@ void backtrack(int row, int n, char state[MAX_N][MAX_N], Result *res,
state[row][col] = 'Q';
cols[col] = diags1[diag1] = diags2[diag2] = true;
// 放置下一行
backtrack(row + 1, n, state, res, cols, diags1, diags2);
backtrack(row + 1, n, state, res, resSize, cols, diags1, diags2);
// 回退:将该格子恢复为空位
state[row][col] = '#';
cols[col] = diags1[diag1] = diags2[diag2] = false;
@ -50,7 +42,7 @@ void backtrack(int row, int n, char state[MAX_N][MAX_N], Result *res,
}
/* 求解 N 皇后 */
Result *nQueens(int n) {
char ***nQueens(int n, int *returnSize) {
char state[MAX_N][MAX_N];
// 初始化 n*n 大小的棋盘,其中 'Q' 代表皇后,'#' 代表空位
for (int i = 0; i < n; ++i) {
@ -63,26 +55,26 @@ Result *nQueens(int n) {
bool diags1[2 * MAX_N - 1] = {false}; // 记录主对角线是否有皇后
bool diags2[2 * MAX_N - 1] = {false}; // 记录副对角线是否有皇后
Result *res = malloc(sizeof(Result));
res->data = (char ***)malloc(sizeof(char **) * MAX_RES);
res->size = 0;
backtrack(0, n, state, res, cols, diags1, diags2);
char ***res = (char ***)malloc(sizeof(char **) * MAX_RES);
*returnSize = 0;
backtrack(0, n, state, res, returnSize, cols, diags1, diags2);
return res;
}
/* Driver Code */
int main() {
int n = 4;
Result *res = nQueens(n);
int returnSize;
char ***res = nQueens(n, &returnSize);
printf("输入棋盘长宽为%d\n", n);
printf("皇后放置方案共有 %d 种\n", res->size);
for (int i = 0; i < res->size; ++i) {
printf("皇后放置方案共有 %d 种\n", returnSize);
for (int i = 0; i < returnSize; ++i) {
for (int j = 0; j < n; ++j) {
printf("[");
for (int k = 0; res->data[i][j][k] != '\0'; ++k) {
printf("%c", res->data[i][j][k]);
if (res->data[i][j][k + 1] != '\0') {
for (int k = 0; res[i][j][k] != '\0'; ++k) {
printf("%c", res[i][j][k]);
if (res[i][j][k + 1] != '\0') {
printf(", ");
}
}
@ -92,13 +84,13 @@ int main() {
}
// 释放内存
for (int i = 0; i < res->size; ++i) {
for (int i = 0; i < returnSize; ++i) {
for (int j = 0; j < n; ++j) {
free(res->data[i][j]);
free(res[i][j]);
}
free(res->data[i]);
free(res[i]);
}
free(res->data);
free(res);
return 0;
}

View File

@ -31,13 +31,11 @@ void constant(int n) {
}
/* 哈希表 */
struct hashTable {
typedef struct {
int key;
int val;
UT_hash_handle hh; // 基于 uthash.h 实现
};
typedef struct hashTable hashTable;
} HashTable;
/* 线性阶 */
void linear(int n) {
@ -57,16 +55,16 @@ void linear(int n) {
free(nodes);
// 长度为 n 的哈希表占用 O(n) 空间
hashTable *h = NULL;
HashTable *h = NULL;
for (int i = 0; i < n; i++) {
hashTable *tmp = malloc(sizeof(hashTable));
HashTable *tmp = malloc(sizeof(HashTable));
tmp->key = i;
tmp->val = i;
HASH_ADD_INT(h, key, tmp);
}
// 内存释放
hashTable *curr, *tmp;
HashTable *curr, *tmp;
HASH_ITER(hh, h, curr, tmp) {
HASH_DEL(h, curr);
free(curr);

View File

@ -1,8 +1,8 @@
/**
* File : build_tree.c
* Created Time: 2023-10-16
* Author : lucas (superrat6@gmail.com)
*/
* File : build_tree.c
* Created Time: 2023-10-16
* Author : lucas (superrat6@gmail.com)
*/
#include "../utils/common.h"
@ -10,12 +10,12 @@
#define MAX_N 1000
/* 构建二叉树:分治 */
TreeNode* dfs(int* preorder, int* inorderMap, int i, int l, int r, int size) {
TreeNode *dfs(int *preorder, int *inorderMap, int i, int l, int r, int size) {
// 子树区间为空时终止
if (r - l < 0)
return NULL;
// 初始化根节点
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->val = preorder[i];
root->left = NULL;
root->right = NULL;
@ -30,13 +30,13 @@ TreeNode* dfs(int* preorder, int* inorderMap, int i, int l, int r, int size) {
}
/* 构建二叉树 */
TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {
TreeNode *buildTree(int *preorder, int preorderSize, int *inorder, int inorderSize) {
// 初始化哈希表,存储 inorder 元素到索引的映射
int* inorderMap = (int*)malloc(sizeof(int) * MAX_N);
int *inorderMap = (int *)malloc(sizeof(int) * MAX_N);
for (int i = 0; i < inorderSize; i++) {
inorderMap[inorder[i]] = i;
}
TreeNode* root = dfs(preorder, inorderMap, 0, 0, inorderSize - 1, inorderSize);
TreeNode *root = dfs(preorder, inorderMap, 0, 0, inorderSize - 1, inorderSize);
free(inorderMap);
return root;
}
@ -52,7 +52,7 @@ int main() {
printf("中序遍历 = ");
printArray(inorder, inorderSize);
TreeNode* root = buildTree(preorder, preorderSize, inorder, inorderSize);
TreeNode *root = buildTree(preorder, preorderSize, inorder, inorderSize);
printf("构建的二叉树为:\n");
printTree(root);

View File

@ -28,7 +28,7 @@ int climbingStairsBacktrack(int n) {
int choices[2] = {1, 2}; // 可选择向上爬 1 或 2 阶
int state = 0; // 从第 0 阶开始爬
int *res = (int *)malloc(sizeof(int));
*res = 0; // 使用 res[0] 记录方案数量
*res = 0; // 使用 res[0] 记录方案数量
int len = sizeof(choices) / sizeof(int);
backtrack(choices, state, n, res, len);
int result = *res;

View File

@ -48,8 +48,10 @@ int main() {
int costSize = sizeof(cost) / sizeof(cost[0]);
printf("输入楼梯的代价列表为 [");
for (int i = 0; i < costSize; i++) {
if (i != costSize - 1) printf("%d, ", cost[i]);
else printf("%d", cost[i]);
if (i != costSize - 1)
printf("%d, ", cost[i]);
else
printf("%d", cost[i]);
}
printf("]\n");

View File

@ -8,11 +8,11 @@
typedef struct Vertex Vertex;
typedef struct Node Node;
typedef struct linkList linkList;
typedef struct LinkedList LinkedList;
void freeVertex(Vertex *);
void freeLinklist(linkList *);
linkList *newLinklist(Vertex *);
void freeLinklist(LinkedList *);
LinkedList *newLinklist(Vertex *);
/* 链表节点 */
struct Node {
@ -34,7 +34,7 @@ struct Vertex {
// 节点值
int val;
// 与其它节点相连接的边的链表
linkList *linked;
LinkedList *list;
// 索引位,标记该顶点在顶点列表中的索引
unsigned int pos;
};
@ -44,52 +44,52 @@ Vertex *newVertex(int val) {
Vertex *vet = (Vertex *)malloc(sizeof(Vertex));
// 为新节点赋值并建立该节点的链表
vet->val = val;
vet->linked = newLinklist(vet);
vet->list = newLinklist(vet);
return vet;
}
/* 顶点内存释放函数 */
void freeVertex(Vertex *val) {
// 释放该顶点和该顶点的链表的内存
freeLinklist(val->linked);
freeLinklist(val->list);
free(val);
}
/* 链表 */
struct linkList {
struct LinkedList {
Node *head;
Node *tail;
};
/* 链表头插法 */
void pushFront(linkList *l, Vertex *val) {
void pushFront(LinkedList *list, Vertex *val) {
Node *temp = newNode();
temp->val = val;
temp->next = l->head->next;
l->head->next = temp;
if (l->tail == l->head) {
l->tail = temp;
temp->next = list->head->next;
list->head->next = temp;
if (list->tail == list->head) {
list->tail = temp;
}
}
/* 链表尾插法 */
void pushBack(linkList *l, Vertex *val) {
void pushBack(LinkedList *list, Vertex *val) {
Node *temp = newNode();
temp->val = val;
temp->next = 0;
l->tail->next = temp;
l->tail = temp;
list->tail->next = temp;
list->tail = temp;
}
/* 根据顶点地址与该顶点连接的删除边 */
void removeLink(linkList *l, Vertex *val) {
Node *temp = l->head->next;
Node *front = l->head;
void removeLink(LinkedList *list, Vertex *val) {
Node *temp = list->head->next;
Node *front = list->head;
while (temp != 0) {
if (temp->val == val) {
front->next = temp->next;
if (l->tail == temp) {
l->tail = front;
if (list->tail == temp) {
list->tail = front;
}
free(temp);
return;
@ -97,21 +97,20 @@ void removeLink(linkList *l, Vertex *val) {
front = temp;
temp = temp->next;
}
if (temp->next == 0) {
printf("vertex not found!\n");
}
}
/* 根据顶点地址删除顶点 */
void removeItem(linkList *l, Vertex *val) {
Node *temp = l->head->next;
Node *front = l->head;
void removeItem(LinkedList *list, Vertex *val) {
Node *temp = list->head->next;
Node *front = list->head;
while (temp != 0) {
if (temp->val == val) {
front->next = temp->next;
if (l->tail == temp) {
l->tail = front;
if (list->tail == temp) {
list->tail = front;
}
freeVertex(val);
free(temp);
@ -120,137 +119,125 @@ void removeItem(linkList *l, Vertex *val) {
front = temp;
temp = temp->next;
}
if (temp->next == 0) {
printf("vertex not found!\n");
}
}
/* 释放链表内存 */
void freeLinklist(linkList *l) {
Node *temp = l->head->next;
void freeLinklist(LinkedList *list) {
Node *temp = list->head->next;
while (temp != 0) {
free(l->head);
l->head = temp;
free(list->head);
list->head = temp;
temp = temp->next;
}
free(l->head);
l->head = 0;
free(l);
free(list->head);
list->head = 0;
free(list);
}
/* 链表构造函数 */
linkList *newLinklist(Vertex *val) {
linkList *newLinklist = (linkList *)malloc(sizeof(linkList));
LinkedList *newLinklist(Vertex *val) {
LinkedList *newLinklist = (LinkedList *)malloc(sizeof(LinkedList));
newLinklist->head = newNode();
newLinklist->head->val = val;
newLinklist->tail = newLinklist->head;
newLinklist->head->next = 0;
return newLinklist;
}
/* 基于邻接链表实现的无向图类结构 */
struct graphAdjList {
Vertex **verticesList; // 邻接表
typedef struct {
Vertex **vertices; // 邻接表
unsigned int size; // 顶点数量
unsigned int capacity; // 顶点容量
};
typedef struct graphAdjList graphAdjList;
} GraphAdjList;
/* 添加边 */
void addEdge(graphAdjList *t, int i, int j) {
void addEdge(GraphAdjList *graph, int i, int j) {
// 越界检查
if (i < 0 || j < 0 || i == j || i >= t->size || j >= t->size) {
if (i < 0 || j < 0 || i == j || i >= graph->size || j >= graph->size) {
printf("Out of range in %s:%d\n", __FILE__, __LINE__);
return;
}
// 查找欲添加边的顶点 vet1 - vet2
Vertex *vet1 = t->verticesList[i];
Vertex *vet2 = t->verticesList[j];
Vertex *vet1 = graph->vertices[i];
Vertex *vet2 = graph->vertices[j];
// 连接顶点 vet1 - vet2
pushBack(vet1->linked, vet2);
pushBack(vet2->linked, vet1);
pushBack(vet1->list, vet2);
pushBack(vet2->list, vet1);
}
/* 删除边 */
void removeEdge(graphAdjList *t, int i, int j) {
void removeEdge(GraphAdjList *graph, int i, int j) {
// 越界检查
if (i < 0 || j < 0 || i == j || i >= t->size || j >= t->size) {
if (i < 0 || j < 0 || i == j || i >= graph->size || j >= graph->size) {
printf("Out of range in %s:%d\n", __FILE__, __LINE__);
return;
}
// 查找欲删除边的顶点 vet1 - vet2
Vertex *vet1 = t->verticesList[i];
Vertex *vet2 = t->verticesList[j];
Vertex *vet1 = graph->vertices[i];
Vertex *vet2 = graph->vertices[j];
// 移除待删除边 vet1 - vet2
removeLink(vet1->linked, vet2);
removeLink(vet2->linked, vet1);
removeLink(vet1->list, vet2);
removeLink(vet2->list, vet1);
}
/* 添加顶点 */
void addVertex(graphAdjList *t, int val) {
void addVertex(GraphAdjList *graph, int val) {
// 若大小超过容量,则扩容
if (t->size >= t->capacity) {
Vertex **tempList = (Vertex **)malloc(sizeof(Vertex *) * 2 * t->capacity);
memcpy(tempList, t->verticesList, sizeof(Vertex *) * t->size);
free(t->verticesList); // 释放原邻接表内存
t->verticesList = tempList; // 指向新邻接表
t->capacity = t->capacity * 2; // 容量扩大至2倍
if (graph->size >= graph->capacity) {
Vertex **tempList = (Vertex **)malloc(sizeof(Vertex *) * 2 * graph->capacity);
memcpy(tempList, graph->vertices, sizeof(Vertex *) * graph->size);
free(graph->vertices); // 释放原邻接表内存
graph->vertices = tempList; // 指向新邻接表
graph->capacity = graph->capacity * 2; // 容量扩大至2倍
}
// 申请新顶点内存并将新顶点地址存入顶点列表
Vertex *newV = newVertex(val); // 建立新顶点
newV->pos = t->size; // 为新顶点标记下标
newV->linked = newLinklist(newV); // 为新顶点建立链表
t->verticesList[t->size] = newV; // 将新顶点加入邻接表
t->size++;
Vertex *newV = newVertex(val); // 建立新顶点
newV->pos = graph->size; // 为新顶点标记下标
newV->list = newLinklist(newV); // 为新顶点建立链表
graph->vertices[graph->size] = newV; // 将新顶点加入邻接表
graph->size++;
}
/* 删除顶点 */
void removeVertex(graphAdjList *t, unsigned int index) {
void removeVertex(GraphAdjList *graph, unsigned int index) {
// 越界检查
if (index < 0 || index >= t->size) {
if (index < 0 || index >= graph->size) {
printf("Out of range in %s:%d\n", __FILE__, __LINE__);
exit(1);
}
Vertex *vet = t->verticesList[index]; // 查找待删节点
Vertex *vet = graph->vertices[index]; // 查找待删节点
if (vet == 0) { // 若不存在该节点,则返回
printf("index is:%d\n", index);
printf("Out of range in %s:%d\n", __FILE__, __LINE__);
return;
}
// 遍历待删除顶点的链表,将所有与待删除结点有关的边删除
Node *temp = vet->linked->head->next;
Node *temp = vet->list->head->next;
while (temp != 0) {
removeLink(temp->val->linked, vet); // 删除与该顶点有关的边
removeLink(temp->val->list, vet); // 删除与该顶点有关的边
temp = temp->next;
}
// 将顶点前移
for (int i = index; i < t->size - 1; i++) {
t->verticesList[i] = t->verticesList[i + 1]; // 顶点前移
t->verticesList[i]->pos--; // 所有前移的顶点索引值减1
for (int i = index; i < graph->size - 1; i++) {
graph->vertices[i] = graph->vertices[i + 1]; // 顶点前移
graph->vertices[i]->pos--; // 所有前移的顶点索引值减1
}
t->verticesList[t->size - 1] = 0; // 将被删除顶点的位置置 0
t->size--;
graph->vertices[graph->size - 1] = 0; // 将被删除顶点的位置置 0
graph->size--;
// 释放内存
freeVertex(vet);
}
/* 打印顶点与邻接矩阵 */
void printGraph(graphAdjList *t) {
void printGraph(GraphAdjList *graph) {
printf("邻接表 =\n");
for (int i = 0; i < t->size; i++) {
Node *n = t->verticesList[i]->linked->head->next;
printf("%d: [", t->verticesList[i]->val);
for (int i = 0; i < graph->size; i++) {
Node *n = graph->vertices[i]->list->head->next;
printf("%d: [", graph->vertices[i]->val);
while (n != 0) {
if (n->next != 0) {
printf("%d, ", n->val->val);
@ -264,14 +251,14 @@ void printGraph(graphAdjList *t) {
}
/* 构造函数 */
graphAdjList *newGraphAdjList(unsigned int verticesCapacity) {
GraphAdjList *newGraphAdjList(unsigned int verticesCapacity) {
// 申请内存
graphAdjList *newGraph = (graphAdjList *)malloc(sizeof(graphAdjList));
GraphAdjList *newGraph = (GraphAdjList *)malloc(sizeof(GraphAdjList));
// 建立顶点表并分配内存
newGraph->verticesList = (Vertex **)malloc(sizeof(Vertex *) * verticesCapacity); // 为顶点列表分配内存
memset(newGraph->verticesList, 0, sizeof(Vertex *) * verticesCapacity); // 顶点列表置 0
newGraph->size = 0; // 初始化顶点数量
newGraph->capacity = verticesCapacity; // 初始化顶点容量
newGraph->vertices = (Vertex **)malloc(sizeof(Vertex *) * verticesCapacity); // 为顶点列表分配内存
memset(newGraph->vertices, 0, sizeof(Vertex *) * verticesCapacity); // 顶点列表置 0
newGraph->size = 0; // 初始化顶点数量
newGraph->capacity = verticesCapacity; // 初始化顶点容量
// 返回图指针
return newGraph;
}

View File

@ -9,7 +9,7 @@
/* Driver Code */
int main() {
/* 初始化无向图 */
graphAdjList *graph = newGraphAdjList(5);
GraphAdjList *graph = newGraphAdjList(5);
// 初始化顶点
addVertex(graph, 1);
addVertex(graph, 3);

View File

@ -7,143 +7,133 @@
#include "../utils/common.h"
/* 基于邻接矩阵实现的无向图类结构 */
struct graphAdjMat {
int *vertices; // 顶点列表
unsigned int **adjMat; // 邻接矩阵,元素代表“边”,索引代表“顶点索引”
unsigned int size; // 顶点数量
unsigned int capacity; // 图容量
};
typedef struct graphAdjMat graphAdjMat;
typedef struct {
int *vertices; // 顶点列表
int **adjMat; // 邻接矩阵,元素代表“边”,索引代表“顶点索引”
int size; // 顶点数量
int capacity; // 图容量
} GraphAdjMat;
/* 添加边 */
// 参数 i, j 对应 vertices 元素索引
void addEdge(graphAdjMat *t, int i, int j) {
void addEdge(GraphAdjMat *graph, int i, int j) {
// 越界检查
if (i < 0 || j < 0 || i >= t->size || j >= t->size || i == j) {
if (i < 0 || j < 0 || i >= graph->size || j >= graph->size || i == j) {
printf("Out of range in %s:%d\n", __FILE__, __LINE__);
exit(1);
}
// 添加边
// 参数 i, j 对应 vertices 元素索引
t->adjMat[i][j] = 1;
t->adjMat[j][i] = 1;
graph->adjMat[i][j] = 1;
graph->adjMat[j][i] = 1;
}
/* 删除边 */
// 参数 i, j 对应 vertices 元素索引
void removeEdge(graphAdjMat *t, int i, int j) {
void removeEdge(GraphAdjMat *graph, int i, int j) {
// 越界检查
if (i < 0 || j < 0 || i >= t->size || j >= t->size || i == j) {
if (i < 0 || j < 0 || i >= graph->size || j >= graph->size || i == j) {
printf("Out of range in %s:%d\n", __FILE__, __LINE__);
exit(1);
}
// 删除边
// 参数 i, j 对应 vertices 元素索引
t->adjMat[i][j] = 0;
t->adjMat[j][i] = 0;
graph->adjMat[i][j] = 0;
graph->adjMat[j][i] = 0;
}
/* 添加顶点 */
void addVertex(graphAdjMat *t, int val) {
void addVertex(GraphAdjMat *graph, int val) {
// 如果实际使用不大于预设空间,则直接初始化新空间
if (t->size < t->capacity) {
t->vertices[t->size] = val; // 初始化新顶点值
for (int i = 0; i < t->size; i++) {
t->adjMat[i][t->size] = 0; // 邻接矩新列阵置0
if (graph->size < graph->capacity) {
graph->vertices[graph->size] = val; // 初始化新顶点值
for (int i = 0; i < graph->size; i++) {
graph->adjMat[i][graph->size] = 0; // 邻接矩新列阵置0
}
memset(t->adjMat[t->size], 0, sizeof(unsigned int) * (t->size + 1)); // 将新增行置 0
t->size++;
memset(graph->adjMat[graph->size], 0, sizeof(int) * (graph->size + 1)); // 将新增行置 0
graph->size++;
return;
}
// 扩容,申请新的顶点数组
int *temp = (int *)malloc(sizeof(int) * (t->size * 2));
memcpy(temp, t->vertices, sizeof(int) * t->size);
temp[t->size] = val;
int *temp = (int *)malloc(sizeof(int) * (graph->size * 2));
memcpy(temp, graph->vertices, sizeof(int) * graph->size);
temp[graph->size] = val;
// 释放原数组
free(t->vertices);
t->vertices = temp;
free(graph->vertices);
graph->vertices = temp;
// 扩容,申请新的二维数组
unsigned int **tempMat = (unsigned int **)malloc(sizeof(unsigned int *) * t->size * 2);
unsigned int *tempMatLine = (unsigned int *)malloc(sizeof(unsigned int) * (t->size * 2) * (t->size * 2));
memset(tempMatLine, 0, sizeof(unsigned int) * (t->size * 2) * (t->size * 2));
for (int k = 0; k < t->size * 2; k++) {
tempMat[k] = tempMatLine + k * (t->size * 2);
int **tempMat = (int **)malloc(sizeof(int *) * graph->size * 2);
int *tempMatLine = (int *)malloc(sizeof(int) * (graph->size * 2) * (graph->size * 2));
memset(tempMatLine, 0, sizeof(int) * (graph->size * 2) * (graph->size * 2));
for (int k = 0; k < graph->size * 2; k++) {
tempMat[k] = tempMatLine + k * (graph->size * 2);
}
for (int i = 0; i < t->size; i++) {
memcpy(tempMat[i], t->adjMat[i], sizeof(unsigned int) * t->size); // 原数据复制到新数组
for (int i = 0; i < graph->size; i++) {
memcpy(tempMat[i], graph->adjMat[i], sizeof(int) * graph->size); // 原数据复制到新数组
}
for (int i = 0; i < t->size; i++) {
tempMat[i][t->size] = 0; // 将新增列置 0
for (int i = 0; i < graph->size; i++) {
tempMat[i][graph->size] = 0; // 将新增列置 0
}
memset(tempMat[t->size], 0, sizeof(unsigned int) * (t->size + 1)); // 将新增行置 0
memset(tempMat[graph->size], 0, sizeof(int) * (graph->size + 1)); // 将新增行置 0
// 释放原数组
free(t->adjMat[0]);
free(t->adjMat);
free(graph->adjMat[0]);
free(graph->adjMat);
// 扩容后,指向新地址
t->adjMat = tempMat; // 指向新的邻接矩阵地址
t->capacity = t->size * 2;
t->size++;
graph->adjMat = tempMat; // 指向新的邻接矩阵地址
graph->capacity = graph->size * 2;
graph->size++;
}
/* 删除顶点 */
void removeVertex(graphAdjMat *t, unsigned int index) {
void removeVertex(GraphAdjMat *graph, int index) {
// 越界检查
if (index < 0 || index >= t->size) {
if (index < 0 || index >= graph->size) {
printf("Out of range in %s:%d\n", __FILE__, __LINE__);
exit(1);
}
for (int i = index; i < t->size - 1; i++) {
t->vertices[i] = t->vertices[i + 1]; // 清除删除的顶点,并将其后所有顶点前移
for (int i = index; i < graph->size - 1; i++) {
graph->vertices[i] = graph->vertices[i + 1]; // 清除删除的顶点,并将其后所有顶点前移
}
t->vertices[t->size - 1] = 0; // 将被前移的最后一个顶点置 0
graph->vertices[graph->size - 1] = 0; // 将被前移的最后一个顶点置 0
// 清除邻接矩阵中删除的列
for (int i = 0; i < t->size - 1; i++) {
for (int i = 0; i < graph->size - 1; i++) {
if (i < index) {
for (int j = index; j < t->size - 1; j++) {
t->adjMat[i][j] = t->adjMat[i][j + 1]; // 被删除列后的所有列前移
for (int j = index; j < graph->size - 1; j++) {
graph->adjMat[i][j] = graph->adjMat[i][j + 1]; // 被删除列后的所有列前移
}
} else {
memcpy(t->adjMat[i], t->adjMat[i + 1], sizeof(unsigned int) * t->size); // 被删除行的下方所有行上移
for (int j = index; j < t->size; j++) {
t->adjMat[i][j] = t->adjMat[i][j + 1]; // 被删除列后的所有列前移
memcpy(graph->adjMat[i], graph->adjMat[i + 1], sizeof(int) * graph->size); // 被删除行的下方所有行上移
for (int j = index; j < graph->size; j++) {
graph->adjMat[i][j] = graph->adjMat[i][j + 1]; // 被删除列后的所有列前移
}
}
}
t->size--;
graph->size--;
}
/* 打印顶点与邻接矩阵 */
void printGraph(graphAdjMat *t) {
if (t->size == 0) {
void printGraph(GraphAdjMat *graph) {
if (graph->size == 0) {
printf("graph is empty\n");
return;
}
printf("顶点列表 = [");
for (int i = 0; i < t->size; i++) {
if (i != t->size - 1) {
printf("%d, ", t->vertices[i]);
for (int i = 0; i < graph->size; i++) {
if (i != graph->size - 1) {
printf("%d, ", graph->vertices[i]);
} else {
printf("%d", t->vertices[i]);
printf("%d", graph->vertices[i]);
}
}
printf("]\n");
printf("邻接矩阵 =\n[\n");
for (int i = 0; i < t->size; i++) {
for (int i = 0; i < graph->size; i++) {
printf(" [");
for (int j = 0; j < t->size; j++) {
if (j != t->size - 1) {
printf("%u, ", t->adjMat[i][j]);
for (int j = 0; j < graph->size; j++) {
if (j != graph->size - 1) {
printf("%u, ", graph->adjMat[i][j]);
} else {
printf("%u", t->adjMat[i][j]);
printf("%u", graph->adjMat[i][j]);
}
}
printf("],\n");
@ -152,26 +142,24 @@ void printGraph(graphAdjMat *t) {
}
/* 构造函数 */
graphAdjMat *newGraphAjdMat(unsigned int numberVertices, int *vertices, unsigned int **adjMat) {
GraphAdjMat *newGraphAjdMat(int numberVertices, int *vertices, int **adjMat) {
// 申请内存
graphAdjMat *newGraph = (graphAdjMat *)malloc(sizeof(graphAdjMat)); // 为图分配内存
newGraph->vertices = (int *)malloc(sizeof(int) * numberVertices * 2); // 为顶点列表分配内存
newGraph->adjMat = (unsigned int **)malloc(sizeof(unsigned int *) * numberVertices * 2); // 为邻接矩阵分配二维内存
unsigned int *temp = (unsigned int *)malloc(sizeof(unsigned int) * numberVertices * 2 * numberVertices * 2); // 为邻接矩阵分配一维内存
newGraph->size = numberVertices; // 初始化顶点数量
newGraph->capacity = numberVertices * 2; // 初始化图容量
GraphAdjMat *newGraph = (GraphAdjMat *)malloc(sizeof(GraphAdjMat)); // 为图分配内存
newGraph->vertices = (int *)malloc(sizeof(int) * numberVertices * 2); // 为顶点列表分配内存
newGraph->adjMat = (int **)malloc(sizeof(int *) * numberVertices * 2); // 为邻接矩阵分配二维内存
int *temp = (int *)malloc(sizeof(int) * numberVertices * 2 * numberVertices * 2); // 为邻接矩阵分配一维内存
newGraph->size = numberVertices; // 初始化顶点数量
newGraph->capacity = numberVertices * 2; // 初始化图容量
// 配置二维数组
for (int i = 0; i < numberVertices * 2; i++) {
newGraph->adjMat[i] = temp + i * numberVertices * 2; // 将二维指针指向一维数组
}
// 赋值
memcpy(newGraph->vertices, vertices, sizeof(int) * numberVertices);
for (int i = 0; i < numberVertices; i++) {
memcpy(newGraph->adjMat[i], adjMat[i], sizeof(unsigned int) * numberVertices); // 将传入的邻接矩阵赋值给结构体内邻接矩阵
memcpy(newGraph->adjMat[i], adjMat[i],
sizeof(int) * numberVertices); // 将传入的邻接矩阵赋值给结构体内邻接矩阵
}
// 返回结构体指针
return newGraph;
}
@ -180,10 +168,10 @@ graphAdjMat *newGraphAjdMat(unsigned int numberVertices, int *vertices, unsigned
int main() {
/* 初始化无向图 */
int vertices[5] = {1, 3, 2, 5, 4};
unsigned int **edge = (unsigned int **)malloc(sizeof(unsigned int *) * 5);
int **edge = (int **)malloc(sizeof(int *) * 5);
// 用于构建二维数组的一维指针
unsigned int *temp = (unsigned int *)malloc(sizeof(unsigned int) * 25);
memset(temp, 0, sizeof(unsigned int) * 25);
int *temp = (int *)malloc(sizeof(int) * 25);
memset(temp, 0, sizeof(int) * 25);
for (int k = 0; k < 5; k++) {
edge[k] = temp + k * 5;
}
@ -195,7 +183,7 @@ int main() {
edge[2][4] = edge[4][2] = 1;
edge[3][4] = edge[4][3] = 1;
// 建立无向图
graphAdjMat *graph = newGraphAjdMat(5, vertices, edge);
GraphAdjMat *graph = newGraphAjdMat(5, vertices, edge);
free(edge);
free(temp);
printf("\n初始化后,图为:\n");

View File

@ -7,16 +7,14 @@
#include "graph_adjacency_list.c"
/* 哈希表 */
struct hashTable {
typedef struct {
unsigned int size;
unsigned int *array;
};
typedef struct hashTable hashTable;
} HashTable;
/* 初始化哈希表 */
hashTable *newHash(unsigned int size) {
hashTable *h = (hashTable *)malloc(sizeof(hashTable));
HashTable *newHash(unsigned int size) {
HashTable *h = (HashTable *)malloc(sizeof(HashTable));
h->array = (unsigned int *)malloc(sizeof(unsigned int) * size);
memset(h->array, 0, sizeof(unsigned int) * size);
h->size = size;
@ -24,12 +22,12 @@ hashTable *newHash(unsigned int size) {
}
/* 标记索引过的顶点 */
void hashMark(hashTable *h, int index) {
void hashMark(HashTable *h, int index) {
h->array[index % h->size] = 1;
}
/* 查询顶点是否已被标记 */
int hashQuery(hashTable *h, int index) {
int hashQuery(HashTable *h, int index) {
// 若顶点已被标记,则返回 1
if (h->array[index % h->size] == 1) {
return 1;
@ -39,24 +37,22 @@ int hashQuery(hashTable *h, int index) {
}
/* 释放哈希表内存 */
void freeHash(hashTable *h) {
void freeHash(HashTable *h) {
free(h->array);
free(h);
}
/* 队列 */
struct queue {
typedef struct {
Vertex **list;
unsigned int size;
int head;
int tail;
};
typedef struct queue queue;
} Queue;
/* 初始化队列 */
queue *newQueue(unsigned int size) {
queue *q = (queue *)malloc(sizeof(queue));
Queue *newQueue(unsigned int size) {
Queue *q = (Queue *)malloc(sizeof(Queue));
q->size = size;
q->list = (Vertex **)malloc(sizeof(Vertex *) * size);
q->head = 0;
@ -66,44 +62,44 @@ queue *newQueue(unsigned int size) {
}
/* 入队 */
void queuePush(queue *q, Vertex *vet) {
void queuePush(Queue *q, Vertex *vet) {
q->list[q->tail] = vet;
q->tail++;
}
/* 出队 */
void queuePop(queue *q) {
void queuePop(Queue *q) {
q->head++;
}
/* 队首元素 */
Vertex *queueTop(queue *q) {
Vertex *queueTop(Queue *q) {
return q->list[q->head];
}
/* 释放队列内存 */
void freeQueue(queue *q) {
void freeQueue(Queue *q) {
free(q->list);
free(q);
}
/* 广度优先遍历 */
// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
Vertex **graphBFS(graphAdjList *t, Vertex *startVet) {
Vertex **graphBFS(GraphAdjList *t, Vertex *startVet) {
// 顶点遍历序列
Vertex **res = (Vertex **)malloc(sizeof(Vertex *) * t->size);
memset(res, 0, sizeof(Vertex *) * t->size);
// 队列用于实现 BFS
queue *que = newQueue(t->size);
Queue *que = newQueue(t->size);
// 哈希表,用于记录已被访问过的顶点
hashTable *visited = newHash(t->size);
HashTable *visited = newHash(t->size);
int resIndex = 0;
queuePush(que, startVet); // 将第一个元素入队
hashMark(visited, startVet->pos); // 标记第一个入队的顶点
// 以顶点 vet 为起点,循环直至访问完所有顶点
while (que->head < que->tail) {
// 遍历该顶点的边链表,将所有与该顶点有连接的,并且未被标记的顶点入队
Node *n = queueTop(que)->linked->head->next;
Node *n = queueTop(que)->list->head->next;
while (n != 0) {
// 查询哈希表,若该索引的顶点已入队,则跳过,否则入队并标记
if (hashQuery(visited, n->val->pos) == 1) {
@ -129,7 +125,7 @@ Vertex **graphBFS(graphAdjList *t, Vertex *startVet) {
/* Driver Code */
int main() {
/* 初始化无向图 */
graphAdjList *graph = newGraphAdjList(3);
GraphAdjList *graph = newGraphAdjList(3);
// 初始化顶点
for (int i = 0; i < 10; i++) {
addVertex(graph, i);
@ -150,7 +146,7 @@ int main() {
printf("\n初始化后,图为:\n");
printGraph(graph);
printf("\n广度优先遍历BFS顶点序列为\n");
Vertex **vets = graphBFS(graph, graph->verticesList[0]);
Vertex **vets = graphBFS(graph, graph->vertices[0]);
// 打印广度优先遍历数组
printf("[");

View File

@ -7,16 +7,14 @@
#include "graph_adjacency_list.c"
/* 哈希表 */
struct hashTable {
typedef struct {
unsigned int size;
unsigned int *array;
};
typedef struct hashTable hashTable;
} HashTable;
/* 初始化哈希表 */
hashTable *newHash(unsigned int size) {
hashTable *h = (hashTable *)malloc(sizeof(hashTable));
HashTable *newHash(unsigned int size) {
HashTable *h = (HashTable *)malloc(sizeof(HashTable));
h->array = (unsigned int *)malloc(sizeof(unsigned int) * size);
memset(h->array, 0, sizeof(unsigned int) * size);
h->size = size;
@ -24,12 +22,12 @@ hashTable *newHash(unsigned int size) {
}
/* 标记索引过的顶点 */
void hashMark(hashTable *h, int index) {
void hashMark(HashTable *h, int index) {
h->array[index % h->size] = 1;
}
/* 查询顶点是否已被标记 */
int hashQuery(hashTable *h, int index) {
int hashQuery(HashTable *h, int index) {
// 若顶点已被标记,则返回 1
if (h->array[index % h->size] == 1) {
return 1;
@ -39,14 +37,14 @@ int hashQuery(hashTable *h, int index) {
}
/* 释放哈希表内存 */
void freeHash(hashTable *h) {
void freeHash(HashTable *h) {
free(h->array);
free(h);
}
/* 深度优先遍历 DFS 辅助函数 */
int resIndex = 0;
void dfs(graphAdjList *graph, hashTable *visited, Vertex *vet, Vertex **res) {
void dfs(GraphAdjList *graph, HashTable *visited, Vertex *vet, Vertex **res) {
if (hashQuery(visited, vet->pos) == 1) {
return; // 跳过已被访问过的顶点
}
@ -54,7 +52,7 @@ void dfs(graphAdjList *graph, hashTable *visited, Vertex *vet, Vertex **res) {
res[resIndex] = vet; // 将顶点存入数组
resIndex++;
// 遍历该顶点链表
Node *n = vet->linked->head->next;
Node *n = vet->list->head->next;
while (n != 0) {
// 递归访问邻接顶点
dfs(graph, visited, n->val, res);
@ -65,12 +63,12 @@ void dfs(graphAdjList *graph, hashTable *visited, Vertex *vet, Vertex **res) {
/* 深度优先遍历 DFS */
// 使用邻接表来表示图,以便获取指定顶点的所有邻接顶点
Vertex **graphDFS(graphAdjList *graph, Vertex *startVet) {
Vertex **graphDFS(GraphAdjList *graph, Vertex *startVet) {
// 顶点遍历序列
Vertex **res = (Vertex **)malloc(sizeof(Vertex *) * graph->size);
memset(res, 0, sizeof(Vertex *) * graph->size);
// 哈希表,用于记录已被访问过的顶点
hashTable *visited = newHash(graph->size);
HashTable *visited = newHash(graph->size);
dfs(graph, visited, startVet, res);
// 释放哈希表内存并将数组索引归零
freeHash(visited);
@ -81,7 +79,7 @@ Vertex **graphDFS(graphAdjList *graph, Vertex *startVet) {
/* Driver Code */
int main() {
graphAdjList *graph = newGraphAdjList(10);
GraphAdjList *graph = newGraphAdjList(10);
for (int i = 0; i < 7; i++) {
addVertex(graph, i);
}
@ -95,7 +93,7 @@ int main() {
printGraph(graph);
// 深度优先遍历 DFS
Vertex **vet = graphDFS(graph, graph->verticesList[0]);
Vertex **vet = graphDFS(graph, graph->vertices[0]);
// 输出遍历结果
printf("\n深度优先遍历DFS顶点序列为\n");

View File

@ -7,7 +7,7 @@
#include "../utils/common.h"
/* 零钱兑换:贪心 */
int coinChangeGreedy(int* coins, int size, int amt) {
int coinChangeGreedy(int *coins, int size, int amt) {
// 假设 coins 列表有序
int i = size - 1;
int count = 0;

View File

@ -7,12 +7,10 @@
#include "../utils/common.h"
/* 物品 */
struct Item {
typedef struct {
int w; // 物品重量
int v; // 物品价值
};
typedef struct Item Item;
} Item;
/* 按照价值密度排序 */
int sortByValueDensity(const void *a, const void *b) {

View File

@ -6,35 +6,29 @@
#include "../utils/common.h"
/* 哈希表默认数组大小 */
/* 哈希表默认大小 */
#define HASH_MAP_DEFAULT_SIZE 100
/* 键值对 int->string */
struct pair {
typedef struct {
int key;
char *val;
};
} Pair;
typedef struct pair pair;
/* 用于表示键值对、键、值的集合 */
struct mapSet {
/* 键值对的集合 */
typedef struct {
void *set;
int len;
};
typedef struct mapSet mapSet;
} MapSet;
/* 基于数组简易实现的哈希表 */
struct arrayHashMap {
pair *buckets[HASH_MAP_DEFAULT_SIZE];
};
typedef struct arrayHashMap arrayHashMap;
typedef struct {
Pair *buckets[HASH_MAP_DEFAULT_SIZE];
} ArrayHashMap;
/* 哈希表初始化函数 */
arrayHashMap *newArrayHashMap() {
arrayHashMap *map = malloc(sizeof(arrayHashMap));
ArrayHashMap *newArrayHashMap() {
ArrayHashMap *map = malloc(sizeof(ArrayHashMap));
return map;
}
@ -45,27 +39,27 @@ int hashFunc(int key) {
}
/* 查询操作 */
const char *get(const arrayHashMap *d, const int key) {
const char *get(const ArrayHashMap *d, const int key) {
int index = hashFunc(key);
const pair *pair = d->buckets[index];
if (pair == NULL)
const Pair *Pair = d->buckets[index];
if (Pair == NULL)
return NULL;
return pair->val;
return Pair->val;
}
/* 添加操作 */
void put(arrayHashMap *d, const int key, const char *val) {
pair *pair = malloc(sizeof(pair));
pair->key = key;
pair->val = malloc(strlen(val) + 1);
strcpy(pair->val, val);
void put(ArrayHashMap *d, const int key, const char *val) {
Pair *Pair = malloc(sizeof(Pair));
Pair->key = key;
Pair->val = malloc(strlen(val) + 1);
strcpy(Pair->val, val);
int index = hashFunc(key);
d->buckets[index] = pair;
d->buckets[index] = Pair;
}
/* 删除操作 */
void removeItem(arrayHashMap *d, const int key) {
void removeItem(ArrayHashMap *d, const int key) {
int index = hashFunc(key);
free(d->buckets[index]->val);
free(d->buckets[index]);
@ -73,8 +67,8 @@ void removeItem(arrayHashMap *d, const int key) {
}
/* 获取所有键值对 */
void pairSet(arrayHashMap *d, mapSet *set) {
pair *entries;
void pairSet(ArrayHashMap *d, MapSet *set) {
Pair *entries;
int i = 0, index = 0;
int total = 0;
@ -85,7 +79,7 @@ void pairSet(arrayHashMap *d, mapSet *set) {
}
}
entries = malloc(sizeof(pair) * total);
entries = malloc(sizeof(Pair) * total);
for (i = 0; i < HASH_MAP_DEFAULT_SIZE; i++) {
if (d->buckets[i] != NULL) {
entries[index].key = d->buckets[i]->key;
@ -100,7 +94,7 @@ void pairSet(arrayHashMap *d, mapSet *set) {
}
/* 获取所有键 */
void keySet(arrayHashMap *d, mapSet *set) {
void keySet(ArrayHashMap *d, MapSet *set) {
int *keys;
int i = 0, index = 0;
int total = 0;
@ -125,7 +119,7 @@ void keySet(arrayHashMap *d, mapSet *set) {
}
/* 获取所有值 */
void valueSet(arrayHashMap *d, mapSet *set) {
void valueSet(ArrayHashMap *d, MapSet *set) {
char **vals;
int i = 0, index = 0;
int total = 0;
@ -150,11 +144,11 @@ void valueSet(arrayHashMap *d, mapSet *set) {
}
/* 打印哈希表 */
void print(arrayHashMap *d) {
void print(ArrayHashMap *d) {
int i;
mapSet set;
MapSet set;
pairSet(d, &set);
pair *entries = (pair *)set.set;
Pair *entries = (Pair *)set.set;
for (i = 0; i < set.len; i++) {
printf("%d -> %s\n", entries[i].key, entries[i].val);
}
@ -164,7 +158,7 @@ void print(arrayHashMap *d) {
/* Driver Code */
int main() {
/* 初始化哈希表 */
arrayHashMap *map = newArrayHashMap();
ArrayHashMap *map = newArrayHashMap();
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)
@ -193,7 +187,7 @@ int main() {
printf("\n遍历键值对 Key->Value\n");
print(map);
mapSet set;
MapSet set;
keySet(map, &set);
int *keys = (int *)set.set;

View File

@ -8,36 +8,33 @@
#include <stdlib.h>
#include <string.h>
/* 键值对 */
struct pair {
int key;
char val[100]; // 假设 val 最大长度为 100
};
// 假设 val 最大长度为 100
#define MAX_SIZE 100
typedef struct pair Pair;
/* 键值对 */
typedef struct {
int key;
char val[MAX_SIZE];
} Pair;
/* 链表节点 */
struct node {
typedef struct Node {
Pair *pair;
struct node *next;
};
typedef struct node Node;
struct Node *next;
} Node;
/* 链式地址哈希表 */
struct hashMapChaining {
typedef struct {
int size; // 键值对数量
int capacity; // 哈希表容量
double loadThres; // 触发扩容的负载因子阈值
int extendRatio; // 扩容倍数
Node **buckets; // 桶数组
};
typedef struct hashMapChaining hashMapChaining;
} HashMapChaining;
/* 构造方法 */
hashMapChaining *initHashMapChaining() {
hashMapChaining *hashMap = (hashMapChaining *)malloc(sizeof(hashMapChaining));
HashMapChaining *initHashMapChaining() {
HashMapChaining *hashMap = (HashMapChaining *)malloc(sizeof(HashMapChaining));
hashMap->size = 0;
hashMap->capacity = 4;
hashMap->loadThres = 2.0 / 3.0;
@ -50,7 +47,7 @@ hashMapChaining *initHashMapChaining() {
}
/* 析构方法 */
void freeHashMapChaining(hashMapChaining *hashMap) {
void freeHashMapChaining(HashMapChaining *hashMap) {
for (int i = 0; i < hashMap->capacity; i++) {
Node *cur = hashMap->buckets[i];
while (cur) {
@ -65,17 +62,17 @@ void freeHashMapChaining(hashMapChaining *hashMap) {
}
/* 哈希函数 */
int hashFunc(hashMapChaining *hashMap, int key) {
int hashFunc(HashMapChaining *hashMap, int key) {
return key % hashMap->capacity;
}
/* 负载因子 */
double loadFactor(hashMapChaining *hashMap) {
double loadFactor(HashMapChaining *hashMap) {
return (double)hashMap->size / (double)hashMap->capacity;
}
/* 查询操作 */
char *get(hashMapChaining *hashMap, int key) {
char *get(HashMapChaining *hashMap, int key) {
int index = hashFunc(hashMap, key);
// 遍历桶,若找到 key 则返回对应 val
Node *cur = hashMap->buckets[index];
@ -89,10 +86,10 @@ char *get(hashMapChaining *hashMap, int key) {
}
/* 添加操作 */
void put(hashMapChaining *hashMap, int key, const char *val);
void put(HashMapChaining *hashMap, int key, const char *val);
/* 扩容哈希表 */
void extend(hashMapChaining *hashMap) {
void extend(HashMapChaining *hashMap) {
// 暂存原哈希表
int oldCapacity = hashMap->capacity;
Node **oldBuckets = hashMap->buckets;
@ -120,7 +117,7 @@ void extend(hashMapChaining *hashMap) {
}
/* 添加操作 */
void put(hashMapChaining *hashMap, int key, const char *val) {
void put(HashMapChaining *hashMap, int key, const char *val) {
// 当负载因子超过阈值时,执行扩容
if (loadFactor(hashMap) > hashMap->loadThres) {
extend(hashMap);
@ -147,7 +144,7 @@ void put(hashMapChaining *hashMap, int key, const char *val) {
}
/* 删除操作 */
void removeKey(hashMapChaining *hashMap, int key) {
void removeKey(HashMapChaining *hashMap, int key) {
int index = hashFunc(hashMap, key);
Node *cur = hashMap->buckets[index];
Node *pre = NULL;
@ -171,7 +168,7 @@ void removeKey(hashMapChaining *hashMap, int key) {
}
/* 打印哈希表 */
void print(hashMapChaining *hashMap) {
void print(HashMapChaining *hashMap) {
for (int i = 0; i < hashMap->capacity; i++) {
Node *cur = hashMap->buckets[i];
printf("[");
@ -186,7 +183,7 @@ void print(hashMapChaining *hashMap) {
/* Driver Code */
int main() {
/* 初始化哈希表 */
hashMapChaining *hashMap = initHashMapChaining();
HashMapChaining *hashMap = initHashMapChaining();
/* 添加操作 */
// 在哈希表中添加键值对 (key, value)

View File

@ -7,31 +7,27 @@
#include "../utils/common.h"
/* 开放寻址哈希表 */
struct pair {
typedef struct {
int key;
char *val;
};
typedef struct pair Pair;
} Pair;
/* 开放寻址哈希表 */
struct hashMapOpenAddressing {
typedef struct {
int size; // 键值对数量
int capacity; // 哈希表容量
double loadThres; // 触发扩容的负载因子阈值
int extendRatio; // 扩容倍数
Pair **buckets; // 桶数组
Pair *TOMBSTONE; // 删除标记
};
typedef struct hashMapOpenAddressing hashMapOpenAddressing;
} HashMapOpenAddressing;
// 函数声明
void extend(hashMapOpenAddressing *hashMap);
void extend(HashMapOpenAddressing *hashMap);
/* 构造方法 */
hashMapOpenAddressing *newHashMapOpenAddressing() {
hashMapOpenAddressing *hashMap = (hashMapOpenAddressing *)malloc(sizeof(hashMapOpenAddressing));
HashMapOpenAddressing *newHashMapOpenAddressing() {
HashMapOpenAddressing *hashMap = (HashMapOpenAddressing *)malloc(sizeof(HashMapOpenAddressing));
hashMap->size = 0;
hashMap->capacity = 4;
hashMap->loadThres = 2.0 / 3.0;
@ -45,7 +41,7 @@ hashMapOpenAddressing *newHashMapOpenAddressing() {
}
/* 析构方法 */
void delHashMapOpenAddressing(hashMapOpenAddressing *hashMap) {
void delHashMapOpenAddressing(HashMapOpenAddressing *hashMap) {
for (int i = 0; i < hashMap->capacity; i++) {
Pair *pair = hashMap->buckets[i];
if (pair != NULL && pair != hashMap->TOMBSTONE) {
@ -56,17 +52,17 @@ void delHashMapOpenAddressing(hashMapOpenAddressing *hashMap) {
}
/* 哈希函数 */
int hashFunc(hashMapOpenAddressing *hashMap, int key) {
int hashFunc(HashMapOpenAddressing *hashMap, int key) {
return key % hashMap->capacity;
}
/* 负载因子 */
double loadFactor(hashMapOpenAddressing *hashMap) {
double loadFactor(HashMapOpenAddressing *hashMap) {
return (double)hashMap->size / (double)hashMap->capacity;
}
/* 搜索 key 对应的桶索引 */
int findBucket(hashMapOpenAddressing *hashMap, int key) {
int findBucket(HashMapOpenAddressing *hashMap, int key) {
int index = hashFunc(hashMap, key);
int firstTombstone = -1;
// 线性探测,当遇到空桶时跳出
@ -93,7 +89,7 @@ int findBucket(hashMapOpenAddressing *hashMap, int key) {
}
/* 查询操作 */
char *get(hashMapOpenAddressing *hashMap, int key) {
char *get(HashMapOpenAddressing *hashMap, int key) {
// 搜索 key 对应的桶索引
int index = findBucket(hashMap, key);
// 若找到键值对,则返回对应 val
@ -105,7 +101,7 @@ char *get(hashMapOpenAddressing *hashMap, int key) {
}
/* 添加操作 */
void put(hashMapOpenAddressing *hashMap, int key, char *val) {
void put(HashMapOpenAddressing *hashMap, int key, char *val) {
// 当负载因子超过阈值时,执行扩容
if (loadFactor(hashMap) > hashMap->loadThres) {
extend(hashMap);
@ -132,7 +128,7 @@ void put(hashMapOpenAddressing *hashMap, int key, char *val) {
}
/* 删除操作 */
void removeItem(hashMapOpenAddressing *hashMap, int key) {
void removeItem(HashMapOpenAddressing *hashMap, int key) {
// 搜索 key 对应的桶索引
int index = findBucket(hashMap, key);
// 若找到键值对,则用删除标记覆盖它
@ -146,7 +142,7 @@ void removeItem(hashMapOpenAddressing *hashMap, int key) {
}
/* 扩容哈希表 */
void extend(hashMapOpenAddressing *hashMap) {
void extend(HashMapOpenAddressing *hashMap) {
// 暂存原哈希表
Pair **bucketsTmp = hashMap->buckets;
int oldCapacity = hashMap->capacity;
@ -167,7 +163,7 @@ void extend(hashMapOpenAddressing *hashMap) {
}
/* 打印哈希表 */
void print(hashMapOpenAddressing *hashMap) {
void print(HashMapOpenAddressing *hashMap) {
for (int i = 0; i < hashMap->capacity; i++) {
Pair *pair = hashMap->buckets[i];
if (pair == NULL) {
@ -183,7 +179,7 @@ void print(hashMapOpenAddressing *hashMap) {
/* Driver Code */
int main() {
// 初始化哈希表
hashMapOpenAddressing *hashmap = newHashMapOpenAddressing();
HashMapOpenAddressing *hashmap = newHashMapOpenAddressing();
// 添加操作
// 在哈希表中添加键值对 (key, val)

View File

@ -9,25 +9,22 @@
#define MAX_SIZE 5000
/* 大顶堆 */
struct maxHeap {
typedef struct {
// size 代表的是实际元素的个数
int size;
// 使用预先分配内存的数组,避免扩容
int data[MAX_SIZE];
};
} MaxHeap;
typedef struct maxHeap maxHeap;
void siftDown(maxHeap *h, int i);
void siftUp(maxHeap *h, int i);
int parent(maxHeap *h, int i);
// 函数声明
void siftDown(MaxHeap *h, int i);
void siftUp(MaxHeap *h, int i);
int parent(MaxHeap *h, int i);
/* 构造函数,根据切片建堆 */
maxHeap *newMaxHeap(int nums[], int size) {
MaxHeap *newMaxHeap(int nums[], int size) {
// 所有元素入堆
maxHeap *h = (maxHeap *)malloc(sizeof(maxHeap));
MaxHeap *h = (MaxHeap *)malloc(sizeof(MaxHeap));
h->size = size;
memcpy(h->data, nums, size * sizeof(int));
for (int i = parent(h, size - 1); i >= 0; i--) {
@ -38,44 +35,44 @@ maxHeap *newMaxHeap(int nums[], int size) {
}
/* 获取左子节点索引 */
int left(maxHeap *h, int i) {
int left(MaxHeap *h, int i) {
return 2 * i + 1;
}
/* 获取右子节点索引 */
int right(maxHeap *h, int i) {
int right(MaxHeap *h, int i) {
return 2 * i + 2;
}
/* 获取父节点索引 */
int parent(maxHeap *h, int i) {
int parent(MaxHeap *h, int i) {
return (i - 1) / 2;
}
/* 交换元素 */
void swap(maxHeap *h, int i, int j) {
void swap(MaxHeap *h, int i, int j) {
int temp = h->data[i];
h->data[i] = h->data[j];
h->data[j] = temp;
}
/* 获取堆大小 */
int size(maxHeap *h) {
int size(MaxHeap *h) {
return h->size;
}
/* 判断堆是否为空 */
int isEmpty(maxHeap *h) {
int isEmpty(MaxHeap *h) {
return h->size == 0;
}
/* 访问堆顶元素 */
int peek(maxHeap *h) {
int peek(MaxHeap *h) {
return h->data[0];
}
/* 元素入堆 */
void push(maxHeap *h, int val) {
void push(MaxHeap *h, int val) {
// 默认情况下,不应该添加这么多节点
if (h->size == MAX_SIZE) {
printf("heap is full!");
@ -90,7 +87,7 @@ void push(maxHeap *h, int val) {
}
/* 元素出堆 */
int pop(maxHeap *h) {
int pop(MaxHeap *h) {
// 判空处理
if (isEmpty(h)) {
printf("heap is empty!");
@ -109,7 +106,7 @@ int pop(maxHeap *h) {
}
/* 从节点 i 开始,从顶至底堆化 */
void siftDown(maxHeap *h, int i) {
void siftDown(MaxHeap *h, int i) {
while (true) {
// 判断节点 i, l, r 中值最大的节点,记为 max
int l = left(h, i);
@ -133,7 +130,7 @@ void siftDown(maxHeap *h, int i) {
}
/* 从节点 i 开始,从底至顶堆化 */
void siftUp(maxHeap *h, int i) {
void siftUp(MaxHeap *h, int i) {
while (true) {
// 获取节点 i 的父节点
int p = parent(h, i);
@ -153,7 +150,7 @@ int main() {
/* 初始化堆 */
// 初始化大顶堆
int nums[] = {9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2};
maxHeap *heap = newMaxHeap(nums, sizeof(nums) / sizeof(int));
MaxHeap *heap = newMaxHeap(nums, sizeof(nums) / sizeof(int));
printf("输入数组并建堆后\n");
printHeap(heap->data, heap->size);

View File

@ -23,26 +23,24 @@ int *twoSumBruteForce(int *nums, int numsSize, int target, int *returnSize) {
}
/* 哈希表 */
struct hashTable {
typedef struct {
int key;
int val;
UT_hash_handle hh; // 基于 uthash.h 实现
};
typedef struct hashTable hashTable;
} HashTable;
/* 哈希表查询 */
hashTable *find(hashTable *h, int key) {
hashTable *tmp;
HashTable *find(HashTable *h, int key) {
HashTable *tmp;
HASH_FIND_INT(h, &key, tmp);
return tmp;
}
/* 哈希表元素插入 */
void insert(hashTable *h, int key, int val) {
hashTable *t = find(h, key);
void insert(HashTable *h, int key, int val) {
HashTable *t = find(h, key);
if (t == NULL) {
hashTable *tmp = malloc(sizeof(hashTable));
HashTable *tmp = malloc(sizeof(HashTable));
tmp->key = key, tmp->val = val;
HASH_ADD_INT(h, key, tmp);
} else {
@ -52,9 +50,9 @@ void insert(hashTable *h, int key, int val) {
/* 方法二:辅助哈希表 */
int *twoSumHashTable(int *nums, int numsSize, int target, int *returnSize) {
hashTable *hashtable = NULL;
HashTable *hashtable = NULL;
for (int i = 0; i < numsSize; i++) {
hashTable *t = find(hashtable, target - nums[i]);
HashTable *t = find(hashtable, target - nums[i]);
if (t != NULL) {
int *res = malloc(sizeof(int) * 2);
res[0] = t->val, res[1] = i;

View File

@ -7,18 +7,16 @@
#include "../utils/common.h"
/* 基于环形数组实现的双向队列 */
struct arrayDeque {
typedef struct {
int *nums; // 用于存储队列元素的数组
int front; // 队首指针,指向队首元素
int queSize; // 尾指针,指向队尾 + 1
int queCapacity; // 队列容量
};
typedef struct arrayDeque arrayDeque;
} ArrayDeque;
/* 构造函数 */
arrayDeque *newArrayDeque(int capacity) {
arrayDeque *deque = (arrayDeque *)malloc(sizeof(arrayDeque));
ArrayDeque *newArrayDeque(int capacity) {
ArrayDeque *deque = (ArrayDeque *)malloc(sizeof(ArrayDeque));
// 初始化数组
deque->queCapacity = capacity;
deque->nums = (int *)malloc(sizeof(int) * deque->queCapacity);
@ -27,28 +25,28 @@ arrayDeque *newArrayDeque(int capacity) {
}
/* 析构函数 */
void delArrayDeque(arrayDeque *deque) {
void delArrayDeque(ArrayDeque *deque) {
free(deque->nums);
deque->queCapacity = 0;
}
/* 获取双向队列的容量 */
int capacity(arrayDeque *deque) {
int capacity(ArrayDeque *deque) {
return deque->queCapacity;
}
/* 获取双向队列的长度 */
int size(arrayDeque *deque) {
int size(ArrayDeque *deque) {
return deque->queSize;
}
/* 判断双向队列是否为空 */
bool empty(arrayDeque *deque) {
bool empty(ArrayDeque *deque) {
return deque->queSize == 0;
}
/* 计算环形数组索引 */
int dequeIndex(arrayDeque *deque, int i) {
int dequeIndex(ArrayDeque *deque, int i) {
// 通过取余操作实现数组首尾相连
// 当 i 越过数组尾部时,回到头部
// 当 i 越过数组头部后,回到尾部
@ -56,7 +54,7 @@ int dequeIndex(arrayDeque *deque, int i) {
}
/* 队首入队 */
void pushFirst(arrayDeque *deque, int num) {
void pushFirst(ArrayDeque *deque, int num) {
if (deque->queSize == capacity(deque)) {
printf("双向队列已满\r\n");
return;
@ -70,7 +68,7 @@ void pushFirst(arrayDeque *deque, int num) {
}
/* 队尾入队 */
void pushLast(arrayDeque *deque, int num) {
void pushLast(ArrayDeque *deque, int num) {
if (deque->queSize == capacity(deque)) {
printf("双向队列已满\r\n");
return;
@ -83,14 +81,14 @@ void pushLast(arrayDeque *deque, int num) {
}
/* 访问队首元素 */
int peekFirst(arrayDeque *deque) {
int peekFirst(ArrayDeque *deque) {
// 访问异常:双向队列为空
assert(empty(deque) == 0);
return deque->nums[deque->front];
}
/* 访问队尾元素 */
int peekLast(arrayDeque *deque) {
int peekLast(ArrayDeque *deque) {
// 访问异常:双向队列为空
assert(empty(deque) == 0);
int last = dequeIndex(deque, deque->front + deque->queSize - 1);
@ -98,7 +96,7 @@ int peekLast(arrayDeque *deque) {
}
/* 队首出队 */
int popFirst(arrayDeque *deque) {
int popFirst(ArrayDeque *deque) {
int num = peekFirst(deque);
// 队首指针向后移动一位
deque->front = dequeIndex(deque, deque->front + 1);
@ -107,14 +105,14 @@ int popFirst(arrayDeque *deque) {
}
/* 队尾出队 */
int popLast(arrayDeque *deque) {
int popLast(ArrayDeque *deque) {
int num = peekLast(deque);
deque->queSize--;
return num;
}
/* 打印队列 */
void printArrayDeque(arrayDeque *deque) {
void printArrayDeque(ArrayDeque *deque) {
int arr[deque->queSize];
// 拷贝
for (int i = 0, j = deque->front; i < deque->queSize; i++, j++) {
@ -127,7 +125,7 @@ void printArrayDeque(arrayDeque *deque) {
int main() {
/* 初始化队列 */
int capacity = 10;
arrayDeque *deque = newArrayDeque(capacity);
ArrayDeque *deque = newArrayDeque(capacity);
pushLast(deque, 3);
pushLast(deque, 2);
pushLast(deque, 5);

View File

@ -7,18 +7,16 @@
#include "../utils/common.h"
/* 基于环形数组实现的队列 */
struct arrayQueue {
typedef struct {
int *nums; // 用于存储队列元素的数组
int front; // 队首指针,指向队首元素
int queSize; // 尾指针,指向队尾 + 1
int queCapacity; // 队列容量
};
typedef struct arrayQueue arrayQueue;
} ArrayQueue;
/* 构造函数 */
arrayQueue *newArrayQueue(int capacity) {
arrayQueue *queue = (arrayQueue *)malloc(sizeof(arrayQueue));
ArrayQueue *newArrayQueue(int capacity) {
ArrayQueue *queue = (ArrayQueue *)malloc(sizeof(ArrayQueue));
// 初始化数组
queue->queCapacity = capacity;
queue->nums = (int *)malloc(sizeof(int) * queue->queCapacity);
@ -27,34 +25,34 @@ arrayQueue *newArrayQueue(int capacity) {
}
/* 析构函数 */
void delArrayQueue(arrayQueue *queue) {
void delArrayQueue(ArrayQueue *queue) {
free(queue->nums);
queue->queCapacity = 0;
}
/* 获取队列的容量 */
int capacity(arrayQueue *queue) {
int capacity(ArrayQueue *queue) {
return queue->queCapacity;
}
/* 获取队列的长度 */
int size(arrayQueue *queue) {
int size(ArrayQueue *queue) {
return queue->queSize;
}
/* 判断队列是否为空 */
bool empty(arrayQueue *queue) {
bool empty(ArrayQueue *queue) {
return queue->queSize == 0;
}
/* 访问队首元素 */
int peek(arrayQueue *queue) {
int peek(ArrayQueue *queue) {
assert(size(queue) != 0);
return queue->nums[queue->front];
}
/* 入队 */
void push(arrayQueue *queue, int num) {
void push(ArrayQueue *queue, int num) {
if (size(queue) == capacity(queue)) {
printf("队列已满\r\n");
return;
@ -68,7 +66,7 @@ void push(arrayQueue *queue, int num) {
}
/* 出队 */
void pop(arrayQueue *queue) {
void pop(ArrayQueue *queue) {
int num = peek(queue);
// 队首指针向后移动一位,若越过尾部则返回到数组头部
queue->front = (queue->front + 1) % queue->queCapacity;
@ -76,7 +74,7 @@ void pop(arrayQueue *queue) {
}
/* 打印队列 */
void printArrayQueue(arrayQueue *queue) {
void printArrayQueue(ArrayQueue *queue) {
int arr[queue->queSize];
// 拷贝
for (int i = 0, j = queue->front; i < queue->queSize; i++, j++) {
@ -89,7 +87,7 @@ void printArrayQueue(arrayQueue *queue) {
int main() {
/* 初始化队列 */
int capacity = 10;
arrayQueue *queue = newArrayQueue(capacity);
ArrayQueue *queue = newArrayQueue(capacity);
/* 元素入队 */
push(queue, 1);

View File

@ -9,16 +9,14 @@
#define MAX_SIZE 5000
/* 基于数组实现的栈 */
struct arrayStack {
typedef struct {
int *data;
int size;
};
typedef struct arrayStack arrayStack;
} ArrayStack;
/* 构造函数 */
arrayStack *newArrayStack() {
arrayStack *s = malloc(sizeof(arrayStack));
ArrayStack *newArrayStack() {
ArrayStack *s = malloc(sizeof(ArrayStack));
// 初始化一个大容量,避免扩容
s->data = malloc(sizeof(int) * MAX_SIZE);
s->size = 0;
@ -26,17 +24,17 @@ arrayStack *newArrayStack() {
}
/* 获取栈的长度 */
int size(arrayStack *s) {
int size(ArrayStack *s) {
return s->size;
}
/* 判断栈是否为空 */
bool isEmpty(arrayStack *s) {
bool isEmpty(ArrayStack *s) {
return s->size == 0;
}
/* 入栈 */
void push(arrayStack *s, int num) {
void push(ArrayStack *s, int num) {
if (s->size == MAX_SIZE) {
printf("stack is full.\n");
return;
@ -46,7 +44,7 @@ void push(arrayStack *s, int num) {
}
/* 访问栈顶元素 */
int peek(arrayStack *s) {
int peek(ArrayStack *s) {
if (s->size == 0) {
printf("stack is empty.\n");
return INT_MAX;
@ -55,7 +53,7 @@ int peek(arrayStack *s) {
}
/* 出栈 */
int pop(arrayStack *s) {
int pop(ArrayStack *s) {
if (s->size == 0) {
printf("stack is empty.\n");
return INT_MAX;
@ -68,7 +66,7 @@ int pop(arrayStack *s) {
/* Driver Code */
int main() {
/* 初始化栈 */
arrayStack *stack = newArrayStack();
ArrayStack *stack = newArrayStack();
/* 元素入栈 */
push(stack, 1);

View File

@ -7,17 +7,15 @@
#include "../utils/common.h"
/* 双向链表节点 */
struct doublyListNode {
typedef struct DoublyListNode {
int val; // 节点值
struct doublyListNode *next; // 后继节点
struct doublyListNode *prev; // 前驱节点
};
typedef struct doublyListNode doublyListNode;
struct DoublyListNode *next; // 后继节点
struct DoublyListNode *prev; // 前驱节点
} DoublyListNode;
/* 构造函数 */
doublyListNode *newDoublyListNode(int num) {
doublyListNode *new = (doublyListNode *)malloc(sizeof(doublyListNode));
DoublyListNode *newDoublyListNode(int num) {
DoublyListNode *new = (DoublyListNode *)malloc(sizeof(DoublyListNode));
new->val = num;
new->next = NULL;
new->prev = NULL;
@ -25,21 +23,19 @@ doublyListNode *newDoublyListNode(int num) {
}
/* 析构函数 */
void delDoublyListNode(doublyListNode *node) {
void delDoublyListNode(DoublyListNode *node) {
free(node);
}
/* 基于双向链表实现的双向队列 */
struct linkedListDeque {
doublyListNode *front, *rear; // 头节点 front ,尾节点 rear
typedef struct {
DoublyListNode *front, *rear; // 头节点 front ,尾节点 rear
int queSize; // 双向队列的长度
};
typedef struct linkedListDeque linkedListDeque;
} LinkedListDeque;
/* 构造函数 */
linkedListDeque *newLinkedListDeque() {
linkedListDeque *deque = (linkedListDeque *)malloc(sizeof(linkedListDeque));
LinkedListDeque *newLinkedListDeque() {
LinkedListDeque *deque = (LinkedListDeque *)malloc(sizeof(LinkedListDeque));
deque->front = NULL;
deque->rear = NULL;
deque->queSize = 0;
@ -47,10 +43,10 @@ linkedListDeque *newLinkedListDeque() {
}
/* 析构函数 */
void delLinkedListdeque(linkedListDeque *deque) {
void delLinkedListdeque(LinkedListDeque *deque) {
// 释放所有节点
for (int i = 0; i < deque->queSize && deque->front != NULL; i++) {
doublyListNode *tmp = deque->front;
DoublyListNode *tmp = deque->front;
deque->front = deque->front->next;
free(tmp);
}
@ -59,18 +55,18 @@ void delLinkedListdeque(linkedListDeque *deque) {
}
/* 获取队列的长度 */
int size(linkedListDeque *deque) {
int size(LinkedListDeque *deque) {
return deque->queSize;
}
/* 判断队列是否为空 */
bool empty(linkedListDeque *deque) {
bool empty(LinkedListDeque *deque) {
return (size(deque) == 0);
}
/* 入队 */
void push(linkedListDeque *deque, int num, bool isFront) {
doublyListNode *node = newDoublyListNode(num);
void push(LinkedListDeque *deque, int num, bool isFront) {
DoublyListNode *node = newDoublyListNode(num);
// 若链表为空,则令 front, rear 都指向node
if (empty(deque)) {
deque->front = deque->rear = node;
@ -93,36 +89,36 @@ void push(linkedListDeque *deque, int num, bool isFront) {
}
/* 队首入队 */
void pushFirst(linkedListDeque *deque, int num) {
void pushFirst(LinkedListDeque *deque, int num) {
push(deque, num, true);
}
/* 队尾入队 */
void pushLast(linkedListDeque *deque, int num) {
void pushLast(LinkedListDeque *deque, int num) {
push(deque, num, false);
}
/* 访问队首元素 */
int peekFirst(linkedListDeque *deque) {
int peekFirst(LinkedListDeque *deque) {
assert(size(deque) && deque->front);
return deque->front->val;
}
/* 访问队尾元素 */
int peekLast(linkedListDeque *deque) {
int peekLast(LinkedListDeque *deque) {
assert(size(deque) && deque->rear);
return deque->rear->val;
}
/* 出队 */
int pop(linkedListDeque *deque, bool isFront) {
int pop(LinkedListDeque *deque, bool isFront) {
if (empty(deque))
return -1;
int val;
// 队首出队操作
if (isFront) {
val = peekFirst(deque); // 暂存头节点值
doublyListNode *fNext = deque->front->next;
DoublyListNode *fNext = deque->front->next;
if (fNext) {
fNext->prev = NULL;
deque->front->next = NULL;
@ -133,7 +129,7 @@ int pop(linkedListDeque *deque, bool isFront) {
// 队尾出队操作
else {
val = peekLast(deque); // 暂存尾节点值
doublyListNode *rPrev = deque->rear->prev;
DoublyListNode *rPrev = deque->rear->prev;
if (rPrev) {
rPrev->next = NULL;
deque->rear->prev = NULL;
@ -146,21 +142,21 @@ int pop(linkedListDeque *deque, bool isFront) {
}
/* 队首出队 */
int popFirst(linkedListDeque *deque) {
int popFirst(LinkedListDeque *deque) {
return pop(deque, true);
}
/* 队尾出队 */
int popLast(linkedListDeque *deque) {
int popLast(LinkedListDeque *deque) {
return pop(deque, false);
}
/* 打印队列 */
void printLinkedListDeque(linkedListDeque *deque) {
void printLinkedListDeque(LinkedListDeque *deque) {
int arr[deque->queSize];
// 拷贝链表中的数据到数组
int i;
doublyListNode *node;
DoublyListNode *node;
for (i = 0, node = deque->front; i < deque->queSize; i++) {
arr[i] = node->val;
node = node->next;
@ -171,7 +167,7 @@ void printLinkedListDeque(linkedListDeque *deque) {
/* Driver Code */
int main() {
/* 初始化双向队列 */
linkedListDeque *deque = newLinkedListDeque();
LinkedListDeque *deque = newLinkedListDeque();
pushLast(deque, 3);
pushLast(deque, 2);
pushLast(deque, 5);

View File

@ -7,16 +7,14 @@
#include "../utils/common.h"
/* 基于链表实现的队列 */
struct linkedListQueue {
typedef struct {
ListNode *front, *rear;
int queSize;
};
typedef struct linkedListQueue linkedListQueue;
} LinkedListQueue;
/* 构造函数 */
linkedListQueue *newLinkedListQueue() {
linkedListQueue *queue = (linkedListQueue *)malloc(sizeof(linkedListQueue));
LinkedListQueue *newLinkedListQueue() {
LinkedListQueue *queue = (LinkedListQueue *)malloc(sizeof(LinkedListQueue));
queue->front = NULL;
queue->rear = NULL;
queue->queSize = 0;
@ -24,7 +22,7 @@ linkedListQueue *newLinkedListQueue() {
}
/* 析构函数 */
void delLinkedListQueue(linkedListQueue *queue) {
void delLinkedListQueue(LinkedListQueue *queue) {
// 释放所有节点
for (int i = 0; i < queue->queSize && queue->front != NULL; i++) {
ListNode *tmp = queue->front;
@ -36,17 +34,17 @@ void delLinkedListQueue(linkedListQueue *queue) {
}
/* 获取队列的长度 */
int size(linkedListQueue *queue) {
int size(LinkedListQueue *queue) {
return queue->queSize;
}
/* 判断队列是否为空 */
bool empty(linkedListQueue *queue) {
bool empty(LinkedListQueue *queue) {
return (size(queue) == 0);
}
/* 入队 */
void push(linkedListQueue *queue, int num) {
void push(LinkedListQueue *queue, int num) {
// 尾节点处添加 node
ListNode *node = newListNode(num);
// 如果队列为空,则令头、尾节点都指向该节点
@ -63,13 +61,13 @@ void push(linkedListQueue *queue, int num) {
}
/* 访问队首元素 */
int peek(linkedListQueue *queue) {
int peek(LinkedListQueue *queue) {
assert(size(queue) && queue->front);
return queue->front->val;
}
/* 出队 */
void pop(linkedListQueue *queue) {
void pop(LinkedListQueue *queue) {
int num = peek(queue);
ListNode *tmp = queue->front;
queue->front = queue->front->next;
@ -78,7 +76,7 @@ void pop(linkedListQueue *queue) {
}
/* 打印队列 */
void printLinkedListQueue(linkedListQueue *queue) {
void printLinkedListQueue(LinkedListQueue *queue) {
int arr[queue->queSize];
// 拷贝链表中的数据到数组
int i;
@ -93,7 +91,7 @@ void printLinkedListQueue(linkedListQueue *queue) {
/* Driver Code */
int main() {
/* 初始化队列 */
linkedListQueue *queue = newLinkedListQueue();
LinkedListQueue *queue = newLinkedListQueue();
/* 元素入队 */
push(queue, 1);

View File

@ -7,23 +7,21 @@
#include "../utils/common.h"
/* 基于链表实现的栈 */
struct linkedListStack {
typedef struct {
ListNode *top; // 将头节点作为栈顶
int size; // 栈的长度
};
typedef struct linkedListStack linkedListStack;
} LinkedListStack;
/* 构造函数 */
linkedListStack *newLinkedListStack() {
linkedListStack *s = malloc(sizeof(linkedListStack));
LinkedListStack *newLinkedListStack() {
LinkedListStack *s = malloc(sizeof(LinkedListStack));
s->top = NULL;
s->size = 0;
return s;
}
/* 析构函数 */
void delLinkedListStack(linkedListStack *s) {
void delLinkedListStack(LinkedListStack *s) {
while (s->top) {
ListNode *n = s->top->next;
free(s->top);
@ -33,26 +31,26 @@ void delLinkedListStack(linkedListStack *s) {
}
/* 获取栈的长度 */
int size(linkedListStack *s) {
int size(LinkedListStack *s) {
assert(s);
return s->size;
}
/* 判断栈是否为空 */
bool isEmpty(linkedListStack *s) {
bool isEmpty(LinkedListStack *s) {
assert(s);
return size(s) == 0;
}
/* 访问栈顶元素 */
int peek(linkedListStack *s) {
int peek(LinkedListStack *s) {
assert(s);
assert(size(s) != 0);
return s->top->val;
}
/* 入栈 */
void push(linkedListStack *s, int num) {
void push(LinkedListStack *s, int num) {
assert(s);
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->next = s->top; // 更新新加节点指针域
@ -62,7 +60,7 @@ void push(linkedListStack *s, int num) {
}
/* 出栈 */
int pop(linkedListStack *s) {
int pop(LinkedListStack *s) {
if (s->size == 0) {
printf("stack is empty.\n");
return INT_MAX;
@ -80,7 +78,7 @@ int pop(linkedListStack *s) {
/* Driver Code */
int main() {
/* 初始化栈 */
linkedListStack *stack = newLinkedListStack();
LinkedListStack *stack = newLinkedListStack();
/* 元素入栈 */
push(stack, 1);

View File

@ -7,26 +7,24 @@
#include "../utils/common.h"
/* 数组表示下的二叉树类 */
struct arrayBinaryTree {
typedef struct {
vector *tree;
};
typedef struct arrayBinaryTree arrayBinaryTree;
} ArrayBinaryTree;
/* 构造函数 */
arrayBinaryTree *newArrayBinaryTree(vector *arr) {
arrayBinaryTree *newABT = malloc(sizeof(arrayBinaryTree));
ArrayBinaryTree *newArrayBinaryTree(vector *arr) {
ArrayBinaryTree *newABT = malloc(sizeof(ArrayBinaryTree));
newABT->tree = arr;
return newABT;
}
/* 节点数量 */
int size(arrayBinaryTree *abt) {
int size(ArrayBinaryTree *abt) {
return abt->tree->size;
}
/* 获取索引为 i 节点的值 */
int val(arrayBinaryTree *abt, int i) {
int val(ArrayBinaryTree *abt, int i) {
// 若索引越界,则返回 INT_MAX ,代表空位
if (i < 0 || i >= size(abt))
return INT_MAX;
@ -49,7 +47,7 @@ int parent(int i) {
}
/* 深度优先遍历 */
void dfs(arrayBinaryTree *abt, int i, const char *order, vector *res) {
void dfs(ArrayBinaryTree *abt, int i, const char *order, vector *res) {
// 若为空位,则返回
if (val(abt, i) == INT_MAX)
return;
@ -73,7 +71,7 @@ void dfs(arrayBinaryTree *abt, int i, const char *order, vector *res) {
}
/* 层序遍历 */
vector *levelOrder(arrayBinaryTree *abt) {
vector *levelOrder(ArrayBinaryTree *abt) {
vector *res = newVector();
// 直接遍历数组
for (int i = 0; i < size(abt); i++) {
@ -86,21 +84,21 @@ vector *levelOrder(arrayBinaryTree *abt) {
}
/* 前序遍历 */
vector *preOrder(arrayBinaryTree *abt) {
vector *preOrder(ArrayBinaryTree *abt) {
vector *res = newVector();
dfs(abt, 0, "pre", res);
return res;
}
/* 中序遍历 */
vector *inOrder(arrayBinaryTree *abt) {
vector *inOrder(ArrayBinaryTree *abt) {
vector *res = newVector();
dfs(abt, 0, "in", res);
return res;
}
/* 后序遍历 */
vector *postOrder(arrayBinaryTree *abt) {
vector *postOrder(ArrayBinaryTree *abt) {
vector *res = newVector();
dfs(abt, 0, "post", res);
return res;
@ -129,7 +127,7 @@ int main() {
vectorPushback(vArr, &arr[i], sizeof(int));
}
// 数组表示下的二叉树类
arrayBinaryTree *abt = newArrayBinaryTree(vArr);
ArrayBinaryTree *abt = newArrayBinaryTree(vArr);
// 访问节点
int i = 1;

View File

@ -7,15 +7,13 @@
#include "../utils/common.h"
/* AVL Tree */
struct aVLTree {
typedef struct {
TreeNode *root;
};
typedef struct aVLTree aVLTree;
} AVLTree;
/* 构建 AVL 树 */
aVLTree *newAVLTree() {
aVLTree *tree = (aVLTree *)malloc(sizeof(aVLTree));
AVLTree *newAVLTree() {
AVLTree *tree = (AVLTree *)malloc(sizeof(AVLTree));
tree->root = NULL;
return tree;
}
@ -134,7 +132,7 @@ TreeNode *insertHelper(TreeNode *node, int val) {
}
/* 插入节点 */
void insert(aVLTree *tree, int val) {
void insert(AVLTree *tree, int val) {
tree->root = insertHelper(tree->root, val);
}
@ -183,12 +181,12 @@ TreeNode *removeHelper(TreeNode *node, int val) {
/* 删除节点 */
// 由于引入了 stdio.h ,此处无法使用 remove 关键词
void removeItem(aVLTree *tree, int val) {
void removeItem(AVLTree *tree, int val) {
TreeNode *root = removeHelper(tree->root, val);
}
/* 查找节点 */
TreeNode *search(aVLTree *tree, int val) {
TreeNode *search(AVLTree *tree, int val) {
TreeNode *cur = tree->root;
// 循环查找,越过叶节点后跳出
while (cur != NULL) {
@ -207,13 +205,13 @@ TreeNode *search(aVLTree *tree, int val) {
return cur;
}
void testInsert(aVLTree *tree, int val) {
void testInsert(AVLTree *tree, int val) {
insert(tree, val);
printf("\n插入节点 %d 后AVL 树为 \n", val);
printTree(tree->root);
}
void testRemove(aVLTree *tree, int val) {
void testRemove(AVLTree *tree, int val) {
removeItem(tree, val);
printf("\n删除节点 %d 后AVL 树为 \n", val);
printTree(tree->root);
@ -222,7 +220,7 @@ void testRemove(aVLTree *tree, int val) {
/* Driver Code */
int main() {
/* 初始化空 AVL 树 */
aVLTree *tree = (aVLTree *)newAVLTree();
AVLTree *tree = (AVLTree *)newAVLTree();
/* 插入节点 */
// 请关注插入节点后AVL 树是如何保持平衡的
testInsert(tree, 1);

View File

@ -7,11 +7,9 @@
#include "../utils/common.h"
/* 二叉搜索树 */
struct binarySearchTree {
typedef struct {
TreeNode *root;
};
typedef struct binarySearchTree binarySearchTree;
} BinarySearchTree;
/* 比较器:从小到大排序 */
int sortIntHelper(const void *a, const void *b) {
@ -32,8 +30,8 @@ TreeNode *buildTree(int nums[], int i, int j) {
return root;
}
binarySearchTree *newBinarySearchTree(int nums[], int size) {
binarySearchTree *bst = (binarySearchTree *)malloc(sizeof(binarySearchTree));
BinarySearchTree *newBinarySearchTree(int nums[], int size) {
BinarySearchTree *bst = (BinarySearchTree *)malloc(sizeof(BinarySearchTree));
TreeNode *root;
// 从小到大排序数组
qsort(nums, size, sizeof(int), sortIntHelper);
@ -44,12 +42,12 @@ binarySearchTree *newBinarySearchTree(int nums[], int size) {
}
/* 获取二叉树根节点 */
TreeNode *getRoot(binarySearchTree *bst) {
TreeNode *getRoot(BinarySearchTree *bst) {
return bst->root;
}
/* 查找节点 */
TreeNode *search(binarySearchTree *bst, int num) {
TreeNode *search(BinarySearchTree *bst, int num) {
TreeNode *cur = bst->root;
// 循环查找,越过叶节点后跳出
while (cur != NULL) {
@ -69,7 +67,7 @@ TreeNode *search(binarySearchTree *bst, int num) {
}
/* 插入节点 */
void insert(binarySearchTree *bst, int num) {
void insert(BinarySearchTree *bst, int num) {
// 若树为空,则初始化根节点
if (bst->root == NULL) {
bst->root = newTreeNode(num);
@ -102,7 +100,7 @@ void insert(binarySearchTree *bst, int num) {
/* 删除节点 */
// 由于引入了 stdio.h ,此处无法使用 remove 关键词
void removeItem(binarySearchTree *bst, int num) {
void removeItem(BinarySearchTree *bst, int num) {
// 若树为空,直接提前返回
if (bst->root == NULL)
return;
@ -154,7 +152,7 @@ void removeItem(binarySearchTree *bst, int num) {
int main() {
/* 初始化二叉搜索树 */
int nums[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
binarySearchTree *bst = newBinarySearchTree(nums, sizeof(nums) / sizeof(int));
BinarySearchTree *bst = newBinarySearchTree(nums, sizeof(nums) / sizeof(int));
printf("初始化的二叉树为\n");
printTree(getRoot(bst));

View File

@ -12,13 +12,10 @@ extern "C" {
#endif
/* 链表节点结构体 */
struct ListNode {
typedef struct ListNode {
int val; // 节点值
struct ListNode *next; // 指向下一节点的引用
};
// typedef 作用是为一种数据类型定义一个新名字
typedef struct ListNode ListNode;
} ListNode;
/* 构造函数,初始化一个新节点 */
ListNode *newListNode(int val) {

View File

@ -72,12 +72,10 @@ static void printLinkedList(ListNode *node) {
printf("%d\n", node->val);
}
struct Trunk {
typedef struct Trunk {
struct Trunk *prev;
char *str;
};
typedef struct Trunk Trunk;
} Trunk;
Trunk *newTrunk(Trunk *prev, char *str) {
Trunk *trunk = (Trunk *)malloc(sizeof(Trunk));

View File

@ -16,14 +16,12 @@ extern "C" {
#define MAX_NODE_SIZE 5000
/* 二叉树节点结构体 */
struct TreeNode {
typedef struct TreeNode {
int val; // 节点值
int height; // 节点高度
struct TreeNode *left; // 左子节点指针
struct TreeNode *right; // 右子节点指针
};
typedef struct TreeNode TreeNode;
} TreeNode;
TreeNode *newTreeNode(int val) {
TreeNode *node;

View File

@ -147,12 +147,10 @@
```c title=""
/* 链表节点结构体 */
struct ListNode {
typedef struct ListNode {
int val; // 节点值
struct ListNode *next; // 指向下一节点的指针
};
typedef struct ListNode ListNode;
} ListNode;
/* 构造函数 */
ListNode *newListNode(int val) {
@ -617,13 +615,11 @@
```c title=""
/* 双向链表节点结构体 */
struct ListNode {
typedef struct ListNode {
int val; // 节点值
struct ListNode *next; // 指向后继节点的指针
struct ListNode *prev; // 指向前驱节点的指针
};
typedef struct ListNode ListNode;
} ListNode;
/* 构造函数 */
ListNode *newListNode(int val) {

View File

@ -181,14 +181,12 @@ AVL 树既是二叉搜索树也是平衡二叉树,同时满足这两类二叉
```c title=""
/* AVL 树节点结构体 */
struct TreeNode {
TreeNode struct TreeNode {
int val;
int height;
struct TreeNode *left;
struct TreeNode *right;
};
typedef struct TreeNode TreeNode;
} TreeNode;
/* 构造函数 */
TreeNode *newTreeNode(int val) {

View File

@ -157,14 +157,12 @@
```c title=""
/* 二叉树节点结构体 */
struct TreeNode {
typedef struct TreeNode {
int val; // 节点值
int height; // 节点高度
struct TreeNode *left; // 左子节点指针
struct TreeNode *right; // 右子节点指针
};
typedef struct TreeNode TreeNode;
} TreeNode;
/* 构造函数 */
TreeNode *newTreeNode(int val) {
@ -594,9 +592,9 @@
<p align="center"><id> &nbsp; 二叉树的最佳与最差情况 </p>
| | 完美二叉树 | 链表 |
| ----------------------------- | ---------- | ---------- |
| 第 $i$ 层的节点数量 | $2^{i-1}$ | $1$ |
| 高度 $h$ 树的叶节点数量 | $2^h$ | $1$ |
| 高度 $h$ 树的节点总数 | $2^{h+1} - 1$ | $h + 1$ |
| 节点总数 $n$ 树的高度 | $\log_2 (n+1) - 1$ | $n - 1$ |
| | 完美二叉树 | 链表 |
| ----------------------- | ------------------ | ------- |
| 第 $i$ 层的节点数量 | $2^{i-1}$ | $1$ |
| 高度 $h$ 树的叶节点数量 | $2^h$ | $1$ |
| 高度 $h$ 树的节点总数 | $2^{h+1} - 1$ | $h + 1$ |
| 节点总数 $n$ 树的高度 | $\log_2 (n+1) - 1$ | $n - 1$ |