以C结构体或C++的“类”代替“第2章中复杂数据类型”,实现“链式线性表”,编写下面6个接口函数:CreateList
时间: 2023-05-29 13:06:34 浏览: 111
、InsertList、DeleteList、FindList、TraverseList和DestroyList。
以下是使用C结构体实现链式线性表的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 链式线性表结构体
typedef struct Node {
int value;
struct Node *next;
} Node, *List;
// 创建链式线性表
List CreateList() {
List head = (List)malloc(sizeof(Node));
head->next = NULL;
return head;
}
// 插入元素到链式线性表中
void InsertList(List head, int value) {
Node *node = (Node*)malloc(sizeof(Node));
node->value = value;
node->next = head->next;
head->next = node;
}
// 从链式线性表中删除指定元素
void DeleteList(List head, int value) {
Node *pre = head, *cur = head->next;
while (cur) {
if (cur->value == value) {
pre->next = cur->next;
free(cur);
return;
}
pre = cur;
cur = cur->next;
}
}
// 查找指定元素在链式线性表中的位置
int FindList(List head, int value) {
Node *cur = head->next;
int pos = 1;
while (cur) {
if (cur->value == value) {
return pos;
}
cur = cur->next;
pos++;
}
return -1;
}
// 遍历链式线性表
void TraverseList(List head) {
Node *cur = head->next;
while (cur) {
printf("%d ", cur->value);
cur = cur->next;
}
printf("\n");
}
// 销毁链式线性表
void DestroyList(List head) {
Node *cur = head->next;
while (cur) {
Node *temp = cur;
cur = cur->next;
free(temp);
}
free(head);
}
int main() {
List head = CreateList();
InsertList(head, 1);
InsertList(head, 2);
InsertList(head, 3);
TraverseList(head);
DeleteList(head, 2);
TraverseList(head);
printf("3 is at position %d\n", FindList(head, 3));
DestroyList(head);
return 0;
}
```
阅读全文