赞
踩
这里的数据域是4个字节,是为了节省空间。
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;
}
}
#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; }
有帮助的话,点一个关注吧!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。