以C结构体或C++的“类”代替“第2章中复杂数据类型”,实现“链式线性表”,编写下面6个接口函数:CreateList、ListPrint、GetElem、ListLengthListlnsert、ListDelete 要求:在计算机中编程测试,并对测试过程中的输入输出,截图说明。编程工具软件推荐VisualC++/CodeBlock/DevC++/VSCode等。
时间: 2023-05-28 17:03:16 浏览: 139
由于我是一个AI语言模型,无法在本地计算机上运行程序,因此无法提供截图。但是,我可以提供以下C语言代码供参考。
链式线性表的结构体定义如下:
```
typedef struct Node {
int data;
struct Node *next;
} Node;
```
接口函数的实现如下:
1. CreateList:创建链表并添加元素
```
Node* CreateList(int n) {
Node *head, *tail, *node;
head = tail = NULL;
int i, data;
for (i = 0; i < n; i++) {
printf("Enter the data for node %d: ", i+1);
scanf("%d", &data);
node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
if (head == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
```
2. ListPrint:打印链表元素
```
void ListPrint(Node *head) {
Node *p = head;
printf("The list is: ");
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
```
3. GetElem:获取链表指定位置的元素
```
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("Error: Index out of range\n");
return -1;
} else {
return p->data;
}
}
```
4. ListLength:获取链表长度
```
int ListLength(Node *head) {
Node *p = head;
int length = 0;
while (p != NULL) {
length++;
p = p->next;
}
return length;
}
```
5. ListInsert:在链表指定位置插入元素
```
Node* ListInsert(Node *head, int i, int data) {
Node *p = head, *q;
int j = 1;
while (p != NULL && j < i) {
q = p;
p = p->next;
j++;
}
if (p == NULL && j < i) {
printf("Error: Index out of range\n");
return head;
}
Node *node = (Node*)malloc(sizeof(Node));
node->data = data;
if (i == 1) {
node->next = head;
head = node;
} else {
q->next = node;
node->next = p;
}
return head;
}
```
6. ListDelete:删除链表指定位置的元素
```
Node* ListDelete(Node *head, int i) {
Node *p = head, *q;
int j = 1;
while (p != NULL && j < i) {
q = p;
p = p->next;
j++;
}
if (p == NULL && j < i) {
printf("Error: Index out of range\n");
return head;
}
if (i == 1) {
head = p->next;
free(p);
} else {
q->next = p->next;
free(p);
}
return head;
}
```
以上是链式线性表的实现,可根据需要进行调用。
阅读全文