c语言代码输入数个字符建立字符顺序表,功能有求表长度,按序号查值,插入元素
时间: 2023-04-07 14:00:43 浏览: 90
可以回答这个问题。建立字符顺序表的代码如下:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
char data[MAXSIZE];
int length;
} SqList;
void InitList(SqList *L) {
L->length = 0;
}
int ListLength(SqList L) {
return L.length;
}
char GetElem(SqList L, int i) {
if (i < 1 || i > L.length) {
printf("Error: index out of range\n");
exit(1);
}
return L.data[i-1];
}
void ListInsert(SqList *L, int i, char e) {
if (i < 1 || i > L->length+1) {
printf("Error: index out of range\n");
exit(1);
}
if (L->length == MAXSIZE) {
printf("Error: list is full\n");
exit(1);
}
for (int j = L->length; j >= i; j--) {
L->data[j] = L->data[j-1];
}
L->data[i-1] = e;
L->length++;
}
int main() {
SqList L;
InitList(&L);
ListInsert(&L, 1, 'a');
ListInsert(&L, 2, 'b');
ListInsert(&L, 3, 'c');
printf("List length: %d\n", ListLength(L));
printf("Element at index 2: %c\n", GetElem(L, 2));
ListInsert(&L, 2, 'd');
printf("Element at index 2 after insertion: %c\n", GetElem(L, 2));
return 0;
}
阅读全文