c语言代码输入数个字符建立字符顺序表,功能有求表长度
时间: 2023-04-07 17:00:39 浏览: 43
可以回答这个问题。建立字符顺序表的代码如下:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
char data[MAXSIZE];
int length;
} SqList;
void InitList(SqList *L) {
L->length = 0;
}
void CreateList(SqList *L) {
printf("请输入字符,以#结束:\n");
char c;
scanf("%c", &c);
while (c != '#') {
L->data[L->length] = c;
L->length++;
scanf("%c", &c);
}
}
int main() {
SqList L;
InitList(&L);
CreateList(&L);
printf("表的长度为:%d\n", L.length);
return 0;
}
相关问题
c语言代码输入数个字符建立字符顺序表,功能有求表长度,按序号查值,插入元素
可以回答这个问题。建立字符顺序表的代码如下:
#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;
}
用C语言输入数个字符建立字符顺序表,在顺序表上练习①求表长度;②按序号查找;③插入元素 的操作。
答案:
① 建立字符顺序表:
```c
#define MAXSIZE 100 //固定长度
typedef struct
{
char ch[MAXSIZE];
int length;
}SqString;
void createString(SqString& s, char cstr[])
{
int len = strlen(cstr);
for(int i=0; i<len; i++)
{
s.ch[i] = cstr[i];
}
s.length = len;
}
```
② 求表长度:
```c
int getLength(SqString s)
{
return s.length;
}
```
③ 按序号查找:
```c
char getElem(SqString s, int i)
{
if(i<1 || i>s.length) exit(EXIT_FAILURE);
return s.ch[i-1];
}
```
④ 插入元素:
```c
void insertElem(SqString& s, int i, char e)
{
if(i<1 || i>s.length+1) exit(EXIT_FAILURE);
if(s.length >= MAXSIZE) exit(EXIT_FAILURE);
for(int j=s.length; j>=i; j--)
{
s.ch[j] = s.ch[j-1];
}
s.ch[i-1] = e;
s.length++;
}
```
请注意,这里给出的只是一个基本的参考实现,实际上可能需要根据具体的应用场景进行调整或优化。如果需要更具体的实现细节或优化建议,可以查阅相关的参考资料或咨询专业人士。