以C结构体或C++的“类 ,实现“链式线性表”,编写下面6个接口函数:CreateList、ListPrint、GetElem、ListLengthListlnsert、ListDeleted的主函数
时间: 2023-05-30 21:01:15 浏览: 43
C语言结构体实现链式线性表的代码如下:
```
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct ListNode {
int data;
struct ListNode *next;
} ListNode;
// 创建链表
ListNode *CreateList(int *arr, int n) {
if (n <= 0) {
return NULL;
}
ListNode *head = (ListNode *)malloc(sizeof(ListNode));
head->next = NULL;
ListNode *p = head;
for (int i = 0; i < n; i++) {
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->data = arr[i];
node->next = NULL;
p->next = node;
p = p->next;
}
return head;
}
// 打印链表
void ListPrint(ListNode *head) {
ListNode *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
// 获取指定位置的元素
int GetElem(ListNode *head, int pos) {
if (pos <= 0) {
return -1;
}
ListNode *p = head->next;
for (int i = 1; i < pos; i++) {
if (p == NULL) {
return -1;
}
p = p->next;
}
return p->data;
}
// 获取链表长度
int ListLength(ListNode *head) {
int len = 0;
ListNode *p = head->next;
while (p != NULL) {
len++;
p = p->next;
}
return len;
}
// 在指定位置插入元素
void ListInsert(ListNode *head, int pos, int data) {
if (pos <= 0) {
return;
}
ListNode *p = head;
for (int i = 1; i < pos; i++) {
if (p == NULL) {
return;
}
p = p->next;
}
ListNode *node = (ListNode *)malloc(sizeof(ListNode));
node->data = data;
node->next = p->next;
p->next = node;
}
// 删除指定位置的元素
void ListDelete(ListNode *head, int pos) {
if (pos <= 0) {
return;
}
ListNode *p = head;
for (int i = 1; i < pos; i++) {
if (p == NULL) {
return;
}
p = p->next;
}
if (p->next == NULL) {
return;
}
ListNode *node = p->next;
p->next = node->next;
free(node);
}
// 主函数
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(int);
ListNode *head = CreateList(arr, n);
printf("原链表:");
ListPrint(head);
printf("链表长度:%d\n", ListLength(head));
printf("第3个元素:%d\n", GetElem(head, 3));
ListInsert(head, 4, 6);
printf("插入元素后的链表:");
ListPrint(head);
ListDelete(head, 2);
printf("删除元素后的链表:");
ListPrint(head);
return 0;
}
```