wordpress默认后台北京seo优化wyhseo
C 语言是一种强大的编程语言,它提供了许多数据结构的实现。在本文档中,我们将讨论一些常见的数据结构,并提供相应的代码示例。
- 数组(Array)
数组是一种线性数据结构,它可以存储相同类型的元素。数组的大小在创建时被确定,并且可以通过索引访问和修改元素。
#include <stdio.h>int main() {int arr[5] = {1, 2, 3, 4, 5};// 访问数组元素printf("第一个元素: %d\n", arr[0]);// 修改数组元素arr[0] = 10;printf("修改后的第一个元素: %d\n", arr[0]);return 0;
}
- 链表(Linked List)
链表是一种动态数据结构,它由节点(Node)组成,每个节点包含一个元素和一个指向下一个节点的指针。
#include <stdio.h>
#include <stdlib.h>// 链表节点
typedef struct Node {int data;struct Node* next;
} Node;int main() {// 创建链表Node* head = NULL;Node* second = NULL;Node* third = NULL;head = (Node*)malloc(sizeof(Node));second = (Node*)malloc(sizeof(Node));third = (Node*)malloc(sizeof(Node));head->data = 1;head->next = second;second->data = 2;second->next = third;third->data = 3;third->next = NULL;// 遍历链表Node* current = head;while (current != NULL) {printf("%d ", current->data);current = current->next;}return 0;
}
- 栈(Stack)
栈是一种后进先出(LIFO)的数据结构。它只允许在栈顶进行插入和删除操作。
#include <stdio.h>
#define MAX_SIZE 100// 栈结构
typedef struct Stack {int arr[MAX_SIZE];int top;
} Stack;// 初始化栈
void init(Stack* stack) {stack->top = -1;
}// 判断栈是否为空
int isEmpty(Stack* stack) {return stack->top == -1;
}// 判断栈是否已满
int isFull(Stack* stack) {return stack->top == MAX_SIZE - 1;
}// 入栈
void push(Stack* stack, int data) {if (isFull(stack)) {printf("栈已满\n");return;}stack->arr[++stack->top] = data;
}// 出栈
int pop(Stack* stack) {if (isEmpty(stack)) {printf("栈为空\n");return -1;}return stack->arr[stack->top--];
}int main() {Stack stack;init(&stack);// 入栈push(&stack, 1);push(&stack, 2);push(&stack, 3);// 出栈printf("%d\n", pop(&stack));printf("%d\n", pop(&stack));printf("%d\n", pop(&stack));return 0;
}
- 队列(Queue)
队列是一种先进先出(FIFO)的数据结构。可以在队尾插入元素,在队头删除元素。
#include <stdio.h>
#define MAX_SIZE 100// 队列结构
typedef struct Queue {int arr[MAX_SIZE];int front;int rear;
} Queue;// 初始化队列
void init(Queue* queue) {queue->front = -1;queue->rear = -1;
}// 判断队列是否为空
int isEmpty(Queue* queue) {return queue->front == -1;
}// 判断队列是否已满
int isFull(Queue* queue) {return (queue->rear + 1) % MAX_SIZE == queue->front;
}// 入队
void enqueue(Queue* queue, int data) {if (isFull(queue)) {printf("队列已满\n");