C语言关于链表数组和队列的笔试题,请用代码举例并写上注释
时间: 2024-05-04 08:20:19 浏览: 99
链表数组:
1. 定义一个链表结构体
```c
struct ListNode {
int val;
struct ListNode *next;
};
```
2. 定义链表数组
```c
struct ListNode* list[10];
```
3. 初始化链表数组
```c
for (int i = 0; i < 10; i++) {
list[i] = NULL;
}
```
4. 在链表数组中插入元素
```c
int index = 5;
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = 10;
newNode->next = NULL;
if (list[index] == NULL) {
list[index] = newNode;
} else {
struct ListNode* p = list[index];
while (p->next != NULL) {
p = p->next;
}
p->next = newNode;
}
```
5. 遍历链表数组
```c
for (int i = 0; i < 10; i++) {
printf("链表%d: ", i);
struct ListNode* p = list[i];
while (p != NULL) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
}
```
队列:
1. 定义一个队列结构体
```c
#define MAX_SIZE 100
struct Queue {
int data[MAX_SIZE];
int front;
int rear;
};
```
2. 初始化队列
```c
void initQueue(struct Queue* q) {
q->front = 0;
q->rear = 0;
}
```
3. 判断队列是否为空
```c
int isEmpty(struct Queue* q) {
return q->front == q->rear;
}
```
4. 判断队列是否已满
```c
int isFull(struct Queue* q) {
return (q->rear + 1) % MAX_SIZE == q->front;
}
```
5. 入队列
```c
void enqueue(struct Queue* q, int val) {
if (isFull(q)) {
printf("队列已满\n");
return;
}
q->data[q->rear] = val;
q->rear = (q->rear + 1) % MAX_SIZE;
}
```
6. 出队列
```c
int dequeue(struct Queue* q) {
if (isEmpty(q)) {
printf("队列为空\n");
return -1;
}
int val = q->data[q->front];
q->front = (q->front + 1) % MAX_SIZE;
return val;
}
```
7. 遍历队列
```c
void traverse(struct Queue* q) {
if (isEmpty(q)) {
printf("队列为空\n");
return;
}
int i = q->front;
while (i != q->rear) {
printf("%d ", q->data[i]);
i = (i + 1) % MAX_SIZE;
}
printf("\n");
}
```
阅读全文