C++实现串的顺序存储结构和堆存储结构并要求运行结果
时间: 2024-03-16 21:44:51 浏览: 88
串的基本操作实现-堆存储结构的实现
5星 · 资源好评率100%
下面是C++实现串的顺序存储结构和堆存储结构的示例代码,并附上相应的运行结果:
1. 串的顺序存储结构
```cpp
#include <iostream>
using namespace std;
#define MAXSIZE 100
typedef struct {
char data[MAXSIZE];
int length;
} SqString;
void StrAssign(SqString &S, char cstr[]) {
int i = 0;
while (cstr[i] != '\0') {
S.data[i] = cstr[i];
i++;
}
S.length = i;
}
void StrPrint(SqString S) {
for (int i = 0; i < S.length; i++) {
cout << S.data[i];
}
cout << endl;
}
int main() {
SqString S;
char cstr[] = "Hello, world!";
StrAssign(S, cstr);
StrPrint(S);
return 0;
}
```
运行结果:
```
Hello, world!
```
2. 串的堆存储结构
```cpp
#include <iostream>
using namespace std;
typedef struct String {
char ch;
String *next;
} StringNode, *StringPtr;
void StrAssign(StringPtr &S, char cstr[]) {
S = new StringNode;
StringPtr p = S;
for (int i = 0; cstr[i] != '\0'; i++) {
p->ch = cstr[i];
p->next = new StringNode;
p = p->next;
}
p->next = NULL;
}
void StrPrint(StringPtr S) {
while (S->next != NULL) {
cout << S->ch;
S = S->next;
}
cout << endl;
}
int main() {
StringPtr S;
char cstr[] = "Hello, world!";
StrAssign(S, cstr);
StrPrint(S);
return 0;
}
```
运行结果:
```
Hello, world!
```
阅读全文