文章目录
- 1.链式串的定义
- 2.初始化
- 3.赋值为0
- 4.赋值操作
- 5.打印操作
- 6.源码
本篇博客中都是带头结点的串。
1.链式串的定义
这里的数据域是4个字节,是为了节省空间。
typedef struct StringNode{
char ch[4]; //按串长分配存储区,ch指向串的基地址
struct StringNode* next;
} StringNode,*String;
2.初始化
bool StrInit(String &S)
{
S = (StringNode*)malloc(sizeof(StringNode)); //开辟空间
if (S == NULL)
return false;
S->next = NULL;
return true;
}
3.赋值为0
将数据域中的元素全部初始化为0
bool StrEmpty(String& S)
{
for (int i = 0; i < 4; ++i)
{
S->ch[i] = 0;
}
return true;
}
4.赋值操作
String StrAssign(String &S)
{
StringNode* s, * r = S; //r为表尾指针
char e = 0;
int i = 0;
cout << "输入你要的字符串:";
cin >> e;
s = (StringNode*)malloc(sizeof(StringNode));
StrEmpty(s);
while (e != '0')
{
s->ch[i] = e;
i++;
if (i >= 4)
{
r->next = s;
r = s;
s = (StringNode*)malloc(sizeof(StringNode));
StrEmpty(s);
i = 0;
}
cout << "输入你要的字符串:";
cin >> e;
}
r->next = s;
r = s;
r->next = NULL;
return S;
}
5.打印操作
当指针不指向空的时候,打印数据域。
void PrintString(String S)
{
S = S->next;
cout << "字符串:";
while (S != NULL)
{
for (int i = 0; i < 4; i++)
{
cout << S->ch[i];
}
S = S->next;
}
}
6.源码
#include<iostream>
using namespace std;
//定义串
typedef struct StringNode{
char ch[4]; //按串长分配存储区,ch指向串的基地址
struct StringNode* next;
} StringNode,*String;
//初始化
bool StrInit(String &S)
{
S = (StringNode*)malloc(sizeof(StringNode)); //开辟空间
if (S == NULL)
return false;
S->next = NULL;
return true;
}
//赋值为0
bool StrEmpty(String& S)
{
for (int i = 0; i < 4; ++i)
{
S->ch[i] = 0;
}
return true;
}
//赋值操作
String StrAssign(String &S)
{
StringNode* s, * r = S; //r为表尾指针
char e = 0;
int i = 0;
cout << "输入你要的字符串:";
cin >> e;
s = (StringNode*)malloc(sizeof(StringNode));
StrEmpty(s);
while (e != '0')
{
s->ch[i] = e;
i++;
if (i >= 4)
{
r->next = s;
r = s;
s = (StringNode*)malloc(sizeof(StringNode));
StrEmpty(s);
i = 0;
}
cout << "输入你要的字符串:";
cin >> e;
}
r->next = s;
r = s;
r->next = NULL;
return S;
}
//打印操作
void PrintString(String S)
{
S = S->next;
cout << "字符串:";
while (S != NULL)
{
for (int i = 0; i < 4; i++)
{
cout << S->ch[i];
}
S = S->next;
}
}
int main()
{
String S;
//初始化
StrInit(S);
//赋值操作
StrAssign(S);
//打印操作
PrintString(S);
return 0;
}
有帮助的话,点一个关注吧!