C语言数据结构代码实现
时间: 2024-06-13 16:02:54 浏览: 213
在C语言中,数据结构是组织和存储数据的方式,常见的数据结构包括数组、链表、队列、栈、树、图等。下面我会简单介绍几个基本数据结构的代码实现:
1. **数组(Array)**:
```c
// 一维整型数组
int arr = {1, 2, 3, 4, 5};
// 多维数组(矩阵)
int matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
```
2. **链表(Linked List)**:
- 单向链表的基本节点结构:
```c
typedef struct Node {
int data;
struct Node* next;
} Node;
```
- 插入节点:
```c
void insert(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
```
3. **队列(Queue)**: 使用数组或链表实现,如使用数组的循环队列:
```c
#define MAX_SIZE 10
int queue[MAX_SIZE];
int front = -1, rear = -1;
void enqueue(int value) {
if ((rear + 1) % MAX_SIZE == front) {
printf("Queue is full.\n");
return;
}
rear = (rear + 1) % MAX_SIZE;
queue[rear] = value;
}
int dequeue() {
if (front == -1) {
printf("Queue is empty.\n");
return -1;
}
int removedValue = queue[front];
front = (front + 1) % MAX_SIZE;
return removedValue;
}
```
4. **栈(Stack)**: 通常使用数组或链表实现,栈顶元素的添加和删除操作(入栈和出栈):
```c
typedef struct Stack {
int top;
int capacity;
int* array;
} Stack;
void push(Stack* stack, int value) {
if (stack->top == stack->capacity - 1) {
// 扩容
stack->capacity *= 2;
stack->array = (int*)realloc(stack->array, sizeof(int) * stack->capacity);
}
stack->array[++stack->top] = value;
}
int pop(Stack* stack) {
if (stack->top == -1) {
printf("Stack is empty.\n");
return -1;
}
return stack->array[stack->top--];
}
```
以上是基础数据结构的一些示例,实际应用中可能还需要处理更多细节和异常情况。
阅读全文
相关推荐












