目录
动态分配链式存储结构
#define ElemType char
typedef struct Strnode{
ElemType data;
struct Strnode *next;
}Strnode,*StrLink;
基本操作
创建串
void StrLink_Creat(StrLink &S)
{
//初始化 创建头节点
S = (StrLink)malloc(sizeof(Strnode));
S->next = NULL;
ElemType data;
Strnode *p = S;
printf("创建串:");
scanf("%c",&data);
while( data != '\n')
{
Strnode *s=(Strnode *)malloc(sizeof(Strnode));
s->data = data;
s->next = p->next;
p->next = s;
p=p->next;
scanf("%c",&data);
}
}
求串长
int StrLink_Length(StrLink S)
{
int i = 0;
while(S->next)
{
S = S->next;
i++;
}
return i;
}
复制
void StrLink_Copy(StrLink S1 ,StrLink &S2)
{
if(!S1->next){
S2->next = NULL;
}
S2->next = NULL;
Strnode *p = S2;
while(S1->next)
{
Strnode *s=(Strnode *)malloc(sizeof(Strnode));
S1 = S1->next;
s->data = S1->data;
s->next = p->next;
p->next = s;
p = p->next;
}
}
两串比较
//S1>S2 返回>0 S1==S2 返回0 S1<S2 返回<0
int StrLink_Compare(StrLink S1,StrLink S2)
{
int temp;
while(S1->next && S2->next)
{
S1 = S1->next;
S2 = S2->next;
temp = S1->data -S2->data;
if(temp){
return temp;
}
}
if((!S1->next) && (!S2->next))
{
return 0;
}else if(!S1->next){
return -1;
}
else if(!S2->next){
return 1;
}
}
查找子串
//返回子串出现位置
int StrLink_Index(StrLink S1,StrLink S2)
{
int i = 0, flag = 0;
Strnode *p1 = S1;
Strnode *p2 = S2;
while(p1->next)
{
if(p1->next->data == p2->next->data)
{
flag = 1;
p1 = p1->next;
p2 = p2->next;
if(!p2->next){
return i+1;
}
}else{
if(flag == 1){
flag = 0;
p2 = S2;
}else{
p1 = p1->next;
i++;
}
}
}
return 0;
}
两串拼接
void StrLink_Concat(StrLink &S1,StrLink S2)
{
Strnode *p = S1;
while(p->next)
{
p=p->next;
}
while(S2->next)
{
Strnode *s=(Strnode *)malloc(sizeof(Strnode));
s->data = S2->next->data;
s->next = p->next;
p->next = s;
p = p->next;
S2 = S2->next;
}
}
清空
void StrLink_Clean(StrLink &S)
{
Strnode *p = S;
while(p->next)
{
Strnode *q = p->next;
p->next = q->next;
free(q);
}
printf("串清空成功\n");
}
判空
void StrLink_IsEmpty(StrLink S)
{
if(S->next){
printf("串不为空\n");
}
else{
printf("串为空\n");
}
}
销毁
void StrLink_Destory(StrLink &S)
{
free(S->next);
S->next = NULL;
printf("销毁成功\n");
}
打印
void StrLink_Print(StrLink S)
{
while(S->next)
{
S = S->next;
printf("%c",S->data);
}
printf("\n");
}
代码实现结果
int main()
{
StrLink S1,S2,S3;
// 1.创建串
printf("串1:");
StrLink_Creat(S1);
printf("串2:");
StrLink_Creat(S2);
printf("串3:");
StrLink_Creat(S3);
// 2.复制
StrLink_Copy(S1,S3);
printf("复制串1后的串3:");
StrLink_Print(S3);
// 3. 比较大小 S1>S2 返回>0 S1==S2 返回0 S1<S2 返回<0
printf("比较大小:%d\n",StrLink_Compare(S1,S2));
// 4.查找子串
printf("查找子串:%d\n",StrLink_Index(S1,S2));
// 5.拼接两串
StrLink_Concat(S1,S2);
printf("拼接后的串1:");
StrLink_Print(S1);
// 6.清空
StrLink_Clean(S1);
// 7.判空
StrLink_IsEmpty(S1);
// 8.销毁
StrLink_Destory(S1);
StrLink_Print(S1);
// 9.求串长
printf("串3的长度为:%d\n",StrLink_Length(S3));
}