5.以C结构体或C++的“类”代替“第2章中复杂数据类型”,实现“链式线性表”,编写下面6个接口函数:CreateList、ListPrint、GetElem、ListLength、ListInsert、ListDelete
时间: 2023-05-30 13:02:26 浏览: 61
C结构体定义:
```c
typedef struct Node {
int data;
struct Node *next;
} Node;
typedef struct List {
Node *head;
int length;
} List;
```
1. CreateList:创建链表
```c
void CreateList(List *list)
{
Node *node = NULL;
Node *tail = NULL;
int data;
// 初始化链表
list->head = NULL;
list->length = 0;
printf("输入链表数据,以-1结束:");
while (1) {
scanf("%d", &data);
if (data == -1) {
break;
}
node = (Node *)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
if (list->head == NULL) {
list->head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
list->length++;
}
}
```
2. ListPrint:打印链表
```c
void ListPrint(List *list)
{
Node *node = list->head;
printf("链表数据:");
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
```
3. GetElem:获取指定位置的节点数据
```c
int GetElem(List *list, int pos, int *data)
{
Node *node = list->head;
int i = 1;
if (pos < 1 || pos > list->length) {
return 0;
}
while (node != NULL) {
if (i == pos) {
*data = node->data;
return 1;
}
i++;
node = node->next;
}
return 0;
}
```
4. ListLength:获取链表长度
```c
int ListLength(List *list)
{
return list->length;
}
```
5. ListInsert:在指定位置插入节点
```c
int ListInsert(List *list, int pos, int data)
{
Node *node = NULL;
Node *prev = NULL;
int i = 1;
if (pos < 1 || pos > list->length + 1) {
return 0;
}
node = (Node *)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
if (pos == 1) {
node->next = list->head;
list->head = node;
} else {
prev = list->head;
while (prev != NULL && i < pos - 1) {
prev = prev->next;
i++;
}
node->next = prev->next;
prev->next = node;
}
list->length++;
return 1;
}
```
6. ListDelete:删除指定位置的节点
```c
int ListDelete(List *list, int pos)
{
Node *node = NULL;
Node *prev = NULL;
int i = 1;
int data;
if (pos < 1 || pos > list->length) {
return 0;
}
if (pos == 1) {
node = list->head;
list->head = list->head->next;
} else {
prev = list->head;
while (prev != NULL && i < pos - 1) {
prev = prev->next;
i++;
}
node = prev->next;
prev->next = node->next;
}
data = node->data;
free(node);
list->length--;
return data;
}
```
阅读全文