(6分)以C结构体或C++的“类”代替“第2章中复杂数据类型”,实现“链式线性表”,编写下面6个接口函数:CreateList、ListPrint、GetElem、ListLength、ListInsert、ListDelete要求:在计算机中编程测试,并对测试过程中的输入输出,截图说明。编程工具软件推荐Visual C++/Code Block/Dev C++/VS Code等。
时间: 2023-05-28 11:07:46 浏览: 114
抱歉,作为AI语言模型无法提供截图功能,以下是C语言代码示例:
```
#include <stdio.h>
#include <stdlib.h>
//定义节点
typedef struct Node {
int data;
struct Node *next;
} Node;
//创建链表
Node *CreateList(int n) {
Node *head = NULL, *tail = NULL, *p = NULL;
int i, data;
for (i = 1; i <= n; i++) {
printf("请输入第%d个节点的值:", i);
scanf("%d", &data);
p = (Node *)malloc(sizeof(Node)); //分配内存
p->data = data;
p->next = NULL;
if (head == NULL) { //第一个节点
head = tail = p;
} else {
tail->next = p;
tail = p;
}
}
return head;
}
//遍历链表并输出节点值
void ListPrint(Node *head) {
Node *p = head;
printf("链表节点的值为:");
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
//获取链表中指定位置的节点值
int GetElem(Node *head, int i) {
Node *p = head;
int j = 1;
while (p != NULL && j < i) {
p = p->next;
j++;
}
if (p == NULL || j > i) {
printf("位置无效\n");
return -1;
} else {
return p->data;
}
}
//获取链表的长度
int ListLength(Node *head) {
Node *p = head;
int len = 0;
while (p != NULL) {
len++;
p = p->next;
}
return len;
}
//在链表中指定位置插入节点
Node *ListInsert(Node *head, int i, int data) {
Node *p = head, *q;
int j = 1;
q = (Node *)malloc(sizeof(Node)); //分配内存
q->data = data;
q->next = NULL;
if (i == 1) { //插入到头部
q->next = head;
head = q;
} else {
while (p != NULL && j < i - 1) {
p = p->next;
j++;
}
if (p == NULL || j > i - 1) {
printf("位置无效\n");
} else {
q->next = p->next;
p->next = q;
}
}
return head;
}
//在链表中指定位置删除节点
Node *ListDelete(Node *head, int i) {
Node *p = head, *q;
int j = 1;
if (i == 1) { //删除头节点
head = head->next;
free(p);
} else {
while (p != NULL && j < i - 1) {
p = p->next;
j++;
}
if (p == NULL || j > i - 1) {
printf("位置无效\n");
} else {
q = p->next;
p->next = q->next;
free(q);
}
}
return head;
}
int main() {
int n, i, data, pos;
Node *head;
printf("请输入链表的节点数:");
scanf("%d", &n);
head = CreateList(n);
ListPrint(head);
printf("请输入要获取节点的位置:");
scanf("%d", &pos);
printf("节点的值为:%d\n", GetElem(head, pos));
printf("链表的长度为:%d\n", ListLength(head));
printf("请输入要插入的位置和值:");
scanf("%d%d", &pos, &data);
head = ListInsert(head, pos, data);
ListPrint(head);
printf("请输入要删除的位置:");
scanf("%d", &pos);
head = ListDelete(head, pos);
ListPrint(head);
return 0;
}
```
阅读全文