0
点赞
收藏
分享

微信扫一扫

数据结构学习(五)

穆风1818 2022-02-12 阅读 118
数据结构

串存储结构

字符串要单独用一种存储结构来存储,称为串存储结构,串指的就是字符串。

串有三种存储方式

定长顺序存储结构(静态)

char str[100]="hello world";

堆分配存储结构(动态数组存储字符串)

void test1()
{
char* str1 = (char*)malloc(10 * sizeof(char)); //申请10个char大小的动态数组
char* str2 = (char*)malloc(10 * sizeof(char));

strcpy_s(str1, strlen(str1)+1,"hello");
strcpy_s(str2, strlen(str2)+1,"world");

int len1 = strlen(str1);
int len2 = strlen(str2);

if (len1 < len1 + len2)
{
str1 = (char*)realloc(str1, (len1+len2+1) * sizeof(char)); //如果不够可以进行申请空间 之前为10,现在扩大为len1+len2+1
}
for (int i = len1; i < len1 + len2; i++)
{
str1[i] = str2[i - len1];
}
str1[len1 + len2] = '\0';
cout << str1 << endl;
}

链式存储结构

#define char_max_size 3
typedef struct linkchar
{
char a[char_max_size];
struct linkchar* next;
};
void printlinkchar(linkchar* c)
{
linkchar* temp = c;
while (temp->next != NULL)
{
for (int i = 0; i < char_max_size; i++)
{
cout << temp->a[i];
}
temp = temp->next;
}
}
linkchar* initlinkchar(const char* a)
{
linkchar* head = (linkchar*)malloc(sizeof(linkchar));
head->next = NULL;

linkchar* temp = head;

int len = strlen(a);
int num = len / char_max_size + 1;

for (int i = 0; i < num; i++)
{
linkchar* b = (linkchar*)malloc(sizeof(linkchar));
temp->next = b;
b->next = NULL;
for (int j = 0; j < char_max_size; j++)
{
if (char_max_size * i + j < len)
{
temp->a[j] = a[char_max_size * i + j];
}
else
{
temp->a[j] = ' ';
}
}
temp = b;
}

return head;
}
举报

相关推荐

0 条评论