老铁们 以C结构体或C++的“类”代替“第2章中复杂数据类型”,实现“链式线性表”,编写下面6个接口函数:CreateList、ListPrint、GetElem、ListLength、ListInsert、ListDelete
时间: 2023-05-28 07:07:04 浏览: 84
1. 创建链表 CreateList:
```c
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* CreateList() {
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
return head;
}
```
2. 打印链表 ListPrint:
```c
void ListPrint(Node* head) {
Node* p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
```
3. 获取元素 GetElem:
```c
int GetElem(Node* head, int index) {
Node* p = head->next;
int i = 0;
while (p != NULL && i < index) {
p = p->next;
i++;
}
if (p == NULL || i > index) {
printf("Error: Index out of range.\n");
return -1;
}
else {
return p->data;
}
}
```
4. 获取链表长度 ListLength:
```c
int ListLength(Node* head) {
Node* p = head->next;
int length = 0;
while (p != NULL) {
length++;
p = p->next;
}
return length;
}
```
5. 插入元素 ListInsert:
```c
void ListInsert(Node* head, int index, int value) {
Node* p = head;
int i = 0;
while (p != NULL && i < index) {
p = p->next;
i++;
}
if (p == NULL || i > index) {
printf("Error: Index out of range.\n");
}
else {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = value;
new_node->next = p->next;
p->next = new_node;
}
}
```
6. 删除元素 ListDelete:
```c
void ListDelete(Node* head, int index) {
Node* p = head;
int i = 0;
while (p->next != NULL && i < index) {
p = p->next;
i++;
}
if (p->next == NULL || i > index) {
printf("Error: Index out of range.\n");
}
else {
Node* q = p->next;
p->next = q->next;
free(q);
}
}
```
阅读全文