用c语言写线性表的基本操作
时间: 2023-08-21 21:02:37 浏览: 94
C语言线性表基本操作
5星 · 资源好评率100%
线性表是一种常见的数据结构,C语言可以使用结构体和指针来实现线性表的基本操作。下面是一些常见的线性表操作:
1. 初始化线性表
```
typedef struct ListNode{
int data;
struct ListNode *next;
} ListNode;
typedef struct {
ListNode *head;
int length;
} List;
void initList(List *list){
list->head = NULL;
list->length = 0;
}
```
2. 插入元素
```
void insert(List *list, int index, int data){
if(index < 0 || index > list->length){
printf("Error: index out of range\n");
return;
}
ListNode *node = (ListNode*)malloc(sizeof(ListNode));
node->data = data;
if(index == 0){
node->next = list->head;
list->head = node;
}else{
ListNode *prev = list->head;
for(int i=0; i<index-1; i++){
prev = prev->next;
}
node->next = prev->next;
prev->next = node;
}
list->length++;
}
```
3. 删除元素
```
void delete(List *list, int index){
if(index < 0 || index >= list->length){
printf("Error: index out of range\n");
return;
}
if(index == 0){
ListNode *temp = list->head;
list->head = temp->next;
free(temp);
}else{
ListNode *prev = list->head;
for(int i=0; i<index-1; i++){
prev = prev->next;
}
ListNode *temp = prev->next;
prev->next = temp->next;
free(temp);
}
list->length--;
}
```
4. 查找元素
```
int search(List *list, int data){
ListNode *node = list->head;
int index = 0;
while(node != NULL){
if(node->data == data){
return index;
}
node = node->next;
index++;
}
return -1;
}
```
5. 修改元素
```
void update(List *list, int index, int data){
if(index < 0 || index >= list->length){
printf("Error: index out of range\n");
return;
}
ListNode *node = list->head;
for(int i=0; i<index; i++){
node = node->next;
}
node->data = data;
}
```
阅读全文