如题:假设以结点大小为l(且附设头结点)的链表结构表示串。试编写实现下列六种串的基本操作 StrAssign, StrCopy, StrCompare, StrLength, Concat和 SubString的函数。
目录
[toc]
PS:
下面是伪代码,不能直接运行,可以进行转换成C语言代码在运行最重要的是这些代码还没有经过验证,可能会有些地方错误,但是 方法是正确的
1.存储结构
//串的链式存储表示
typedef struct{
char ch
LStrNode *next;
}LStrNode,*LString;
2.生成值相等的串常量
Status StrAssign(LString &s,LString t)
{
s = (LStrNode*)malloc(sizeof(LStrNode)); //创建头结点
if(!s)
exit(0);
for(p = s,q = t -> next;q;q = q -> next,p = p -> next)
{
r = (LStrNode*)malloc(sizeof(LStrNode)); //创建新节点
if(!r)
exit(0);
r -> ch = q -> ch;
p -> next = r; //链接新节点
p = r;
}
p -> next = NULL;
}
3.字符串复制
Status StrCopy(LString &s,LString t)
{
//将t的部分信息复制到s
for(p = s -> next,q = t -> next;p&&q;q = q -> next,p = p -> next)
{
p -> ch = q -> ch;
pre = p; //保存s的尾节点地址
}
while(q) //s长度不够需要增加长度
{
p = (LStrNode*)malloc(sizeof(LStrNode)); //创建新节点
if(!r)
exit(0);
p -> ch = q -> ch;
pre -> next = p;
pre = p;
}
p -> next = NULL;
}
4.字符串比较
int StrCompare(LString s,LString t)
{
p = s;
q = t;
while(p && q && p -> ch == q ->ch)
{
p = p -> next;
q = q -> next;
}
if(p && q)
{
return 0; //不相等
}
else
{
return 1; //相等
}
}
5.串长度
int StrLength(LString s)
{
for(i = 0,p = s -> next;p;i++,p = p -> next);
return i;
}
6.串连接
Status Concat(LString &s,LString t1, LString t2)
{
s = (LStrNode*)malloc(sizeof(LStrNode)); //创建头结点
if(!s)
exit(0);
for(i = 0,q = t1 -> next;q;i++,q -> next);
for(j = 0,r = t2 -> next;r;i++,r -> next);
for(k = 0,p = s -> next,q = t1 - > next;k < i; k++,p = p -> next,q = q -> next)
{
tem = (LStrNode*)malloc(sizeof(LStrNode));
if(!tem)
exit(0);
tem -> ch = t1 -> ch;
p -> next = tem;
p = tem;
}
for(k = 0,q = t2 - > next;k < i; k++,p = p -> next,q = q -> next)
{
tem = (LStrNode*)malloc(sizeof(LStrNode));
if(!tem)
exit(0);
tem -> ch = t2 -> ch;
p -> next = tem;
p = tem;
}
p -> next = NULL;
}
7.用sub返回串s的第pos个字符起长度为len的子串
Status SubString(LString &sub,LString s,int pos,int len)
{
i = StrLength(s); //获得串s 长度
if(pos < 1 || pos > i)
return error;
p = s -> next;
j = 1;
while(j != pos) //定位到pos
{
p = p -> next;
j++;
}
for(;j < pos + len;j++)//复制ch
{
sub -> ch = p -> next;
p = p -> next;
sub = sub -> next;
}
sub -> next = NULL;
}