帮我写一个C语言版本的单链表,要求不适用动态内存分配
时间: 2023-04-05 10:04:40 浏览: 150
好的,以下是一个C语言版本的单链表,不使用动态内存分配:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct Node {
int data;
struct Node* next;
} Node;
Node nodes[MAX_SIZE];
int nodeCount = 0;
Node* createNode(int data) {
Node* node = &nodes[nodeCount++];
node->data = data;
node->next = NULL;
return node;
}
void insertNode(Node** head, int data) {
Node* node = createNode(data);
if (*head == NULL) {
*head = node;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = node;
}
}
void deleteNode(Node** head, int data) {
if (*head == NULL) {
return;
}
if ((*head)->data == data) {
Node* temp = *head;
*head = (*head)->next;
temp->next = NULL;
return;
}
Node* current = *head;
while (current->next != NULL && current->next->data != data) {
current = current->next;
}
if (current->next != NULL) {
Node* temp = current->next;
current->next = current->next->next;
temp->next = NULL;
}
}
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
printList(head);
deleteNode(&head, 2);
printList(head);
return 0;
}
```
这个单链表使用一个静态数组来存储节点,最多可以存储100个节点。在创建节点时,我们返回数组中的一个空闲节点,而不是使用动态内存分配。这个单链表包含了插入节点、删除节点和打印链表的基本操作。
阅读全文