做外卖网站的模板,设计基础网站推荐,网络营销的特点举例说明,梧州网站seoC 语言是一种强大的编程语言#xff0c;它提供了许多数据结构的实现。在本文档中#xff0c;我们将讨论一些常见的数据结构#xff0c;并提供相应的代码示例。
数组#xff08;Array#xff09;
数组是一种线性数据结构#xff0c;它可以存储相同类型的元素。数组的大小…C 语言是一种强大的编程语言它提供了许多数据结构的实现。在本文档中我们将讨论一些常见的数据结构并提供相应的代码示例。
数组Array
数组是一种线性数据结构它可以存储相同类型的元素。数组的大小在创建时被确定并且可以通过索引访问和修改元素。
#include stdio.hint 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);