假设线性表采取带头结点的链式存储结构,写出以下算法并用C语言实现。 (1)定义线性表的数据结构,并对其进行初始化。 (2)在线性表的第i个元素位置插入一个元素e。 (3)删除线性表中的第i个元素,并把第i个元素的值用变量e带回。
时间: 2024-03-03 10:49:58 浏览: 110
好的,以下是对应的C语言代码实现:
```
#include <stdio.h>
#include <stdlib.h>
// 线性表的结构体
typedef struct Node {
int data;
struct Node* next;
} Node, *List;
// 初始化线性表
void initList(List* L) {
*L = (Node*)malloc(sizeof(Node));
(*L)->next = NULL;
}
// 在第i个位置插入元素e
int insert(List L, int i, int e) {
Node* p = L;
int j = 0;
while (p != NULL && j < i - 1) {
p = p->next;
j++;
}
if (p == NULL || j > i - 1) {
return 0;
}
Node* q = (Node*)malloc(sizeof(Node));
q->data = e;
q->next = p->next;
p->next = q;
return 1;
}
// 删除第i个元素,并把值带回e
int delete(List L, int i, int* e) {
Node* p = L;
int j = 0;
while (p->next != NULL && j < i - 1) {
p = p->next;
j++;
}
if (p->next == NULL || j > i - 1) {
return 0;
}
Node* q = p->next;
*e = q->data;
p->next = q->next;
free(q);
return 1;
}
int main() {
List L;
initList(&L);
insert(L, 1, 1);
insert(L, 2, 2);
insert(L, 3, 3);
int e;
delete(L, 2, &e);
printf("%d\n", e); // 输出2
return 0;
}
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)