数据结构中c语言的基础代码
时间: 2023-06-24 12:08:51 浏览: 59
以下是一些常见的数据结构在C语言中的基础代码实现:
## 数组
### 声明一个数组
```c
int array[10]; // 声明一个包含10个整数的数组
```
### 给数组赋值
```c
array[0] = 1;
array[1] = 2;
// ...
array[9] = 10;
```
### 访问数组元素
```c
int x = array[2]; // 获取数组中下标为2的元素
```
### 遍历数组
```c
for (int i = 0; i < 10; i++) {
printf("%d\n", array[i]);
}
```
## 链表
### 定义链表节点
```c
struct ListNode {
int val;
struct ListNode *next;
};
```
### 创建链表节点
```c
struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
node->val = 1;
node->next = NULL;
```
### 遍历链表
```c
struct ListNode *p = head;
while (p != NULL) {
printf("%d\n", p->val);
p = p->next;
}
```
### 插入节点
```c
struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
node->val = 2;
node->next = head->next;
head->next = node;
```
### 删除节点
```c
struct ListNode *p = head;
while (p->next != NULL && p->next->val != val) {
p = p->next;
}
if (p->next != NULL) {
struct ListNode *tmp = p->next;
p->next = p->next->next;
free(tmp);
}
```
## 栈
### 定义栈
```c
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1;
```
### 入栈
```c
void push(int val) {
if (top == MAX_SIZE - 1) {
printf("Stack is full\n");
return;
}
top++;
stack[top] = val;
}
```
### 出栈
```c
int pop() {
if (top == -1) {
printf("Stack is empty\n");
return -1;
}
int val = stack[top];
top--;
return val;
}
```
## 队列
### 定义队列
```c
#define MAX_SIZE 100
int queue[MAX_SIZE];
int front = 0;
int rear = -1;
```
### 入队
```c
void enqueue(int val) {
if (rear == MAX_SIZE - 1) {
printf("Queue is full\n");
return;
}
rear++;
queue[rear] = val;
}
```
### 出队
```c
int dequeue() {
if (front > rear) {
printf("Queue is empty\n");
return -1;
}
int val = queue[front];
front++;
return val;
}
```