c语言建立一个顺序表
时间: 2024-09-24 10:23:46 浏览: 55
在C语言中,可以使用结构体(struct)和数组来创建一个简单的顺序表(也叫线性表)。这里是一个基本的例子:
```c
// 定义一个元素结构体,包含数据域和指向下一项的链接域
typedef struct Node {
int data; // 数据域
struct Node* next; // 链接域,指向下一个节点
} Node;
// 定义顺序表类型的变量
typedef struct {
Node* head; // 表头,指向第一个元素
int size; // 表长度
} List;
// 初始化顺序表
void init_list(List* list) {
list->head = NULL;
list->size = 0;
}
// 插入元素到列表末尾
void insert(List* list, int value) {
Node* newNode = (Node*)malloc(sizeof(Node)); // 动态分配内存
if (newNode == NULL) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = value;
newNode->next = NULL;
if (list->head == NULL) {
list->head = newNode;
} else {
Node* current = list->head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
list->size++;
}
// 删除指定位置的元素
void delete(List* list, int index) {
if (index >= 0 && index < list->size) {
if (index == 0) {
Node* temp = list->head;
list->head = temp->next;
} else {
Node* current = list->head;
for (int i = 0; i < index - 1; i++) {
current = current->next;
}
Node* temp = current->next;
current->next = temp->next;
}
free(temp); // 释放删除的节点内存
list->size--;
} else {
printf("Invalid index.\n");
}
}
阅读全文
相关推荐


















