版权声明:转载标明出处即可 https://blog.csdn.net/hpu2022/article/details/84331057
用链表的方法来写串真的是太麻烦了(下回更新一个用动态数组写的)。
下面是我简单实现的链式串的几个功能,没办法,数据结构老师不给代码,这些完全是我自己想的。
应该没什么逻辑上的错误,如有发现还请提出来。
#include <iostream>
#include <cstring>
using namespace std;
const int SIZE = 80 + 7;
typedef struct Chunk{
char ch[SIZE]; // 结点类型和大小
struct Chunk *next;
} Chunk;
typedef struct {
Chunk *head, *tail; // 串的头指针和尾指针
int curlen; // 串的长度
} LString;
bool StrInit(LString &S)
{
S.head = NULL;
S.head = new Chunk; // 初始分配第一个节点
S.tail = S.head;
S.tail->next = NULL;
if( !S.head)
return false;
else
return true;
}
bool StrAssign(LString &S, Chunk *s2)
{
LString s1, tmp;
s1.head = S.head->next;
while(s1.head != NULL) // 如果是赋值就删除除出第一个结点外的所有节点
{
tmp.head = s1.head;
s1.head = s1.head->next;
delete tmp.head;
}
strcpy(S.head->ch, s2->ch); // 赋值到头结点
return true;
}
bool StrDelete(LString &S);
bool StrCopy(LString &s1, const LString &s2)
{
StrDelete(s1); // 先将第一个串清空成空串
s1.curlen = s2.curlen; // 先复制长度值
LString i = s2;
while(i.head != NULL) // 以此可以访问到s2中所有的结点
{
Chunk *tmp = new Chunk; // 新定义一个结点,并分配空间
strcpy(tmp->ch, i.head->ch);
tmp->next = i.head->next;
if(i.head == NULL) // 如果头结点为空
{
s1.head = tmp;
s1.tail = tmp;
}
else
{
s1.tail->next = tmp; // 插入在尾结点的后面
s1.tail = s1.tail->next; // 尾指针后移
}
i.head = i.head->next; // i后移到下一个节点
}
}
bool StrDelete(LString &S) // 删除所有节点,使称为空串
{
LString tmp;
while(S.head != NULL)
{
tmp.head = S.head;
S.head = S.head->next;
delete tmp.head;
}
S.tail = S.head; // 都置位空
return true;
}
bool StrSwap(LString &s1, LString &s2) // 交换两个串
{
LString tmp;
tmp = s1;
s1 = s2;
s2 = tmp;
return true;
}
int StrSize(const LString &S)
{
return S.curlen; // 返回的是结点的个数
}
int main()
{
LString S;
StrInit(S);
cin >> S.head->ch;
cout << S.head->ch;
return 0;
}