作者在 2015-08-04 11:48:05 发布以下内容
#include <stdio.h>
#include <stdlib.h>
#define maximum 5
typedef struct blocklink
{
char data[maximum];
struct blocklink *next;
}BLOCKLINK;
int StringlengthBL(BLOCKLINK *h)//整个块链中字符的个数
{
BLOCKLINK *p=h;
int count=0;
int i=0;
while(p!=NULL)
{
if(i%maximum==0)
p=p->next;
if(p!=NULL)
{
if(p->data[i%maximum]!='$')
count++;
}
i++;
}
return count;
}
int StringLength(char *h)//一个块中链的长度
{
int count=0;
while(h[count]>0)
count++;
return count;
}
BLOCKLINK *CreatBLink(char *t)//把一个字符数组中的元素存储到块链中
{
BLOCKLINK *s,*p,*h;
int i;
p=h=(BLOCKLINK *)malloc(sizeof(BLOCKLINK));
h->next=NULL;
i=0;
while(i<StringLength(t))
{
if(i%maximum==0)//如果i=0的话那么就新建一个节点
{
s=(BLOCKLINK*)malloc(sizeof(BLOCKLINK));
p->next=s;
s->next=NULL;
p=s;
}
s->data[i%maximum]=t[i];
i++;
}
while(i%maximum!=0)
{
s->data[i%maximum]='$';
i++;
}
return h;
}
void Replace(BLOCKLINK *h,char *t,int i)//用t替换由h的第i字符开始的若干串
{
int len=StringLength(t);
if(i<1||i>StringlengthBL(h)||i<0)
{
printf("参数不合理,无法完成操作\n");
return;
}
BLOCKLINK *p=h;
int k;
for(k=0;k<=(i-1)%maximum;k++)//找到第i位置所在的块
p=p->next;
int count=0;
k=(i-1)%maximum;
while(count<len)
{
p->data[k%maximum]=t[count];
count++;
k++;
if(k%maximum==0)
p=p->next;
}
}
void SubStr(BLOCKLINK *h,char *t,int i,int len)
{
if(i<1||i>StringlengthBL(h)||len<0||i-1+len>StringlengthBL(h))//从第i 个开始len个字符相当于i-1+len
{
printf("参数不合理,无法完成操作!\n");
return;
}
BLOCKLINK *p=h;
int k;
for(k=0;k<=(i-1)%maximum;k++)
p=p->next;
int count=0;
k=(i-1)%maximum;
while(count<len)
{
if(p->data[k%maximum]!='$')
{
t[count]=p->data[k%maximum];
count++;
}
k++;
if(k%maximum==0)
p=p->next;
}
}
void StrCon(BLOCKLINK *h,char *t)
{
BLOCKLINK *p,*s;
p=h;
while(p->next!=NULL)
p=p->next;
int i;
for(i=0;i<StringLength(t);i++)
{
if(i%maximum==0)
{
s=(BLOCKLINK *)malloc(sizeof(BLOCKLINK));
p->next=s;
s->next=NULL;
p=s;
}
p->data[i%maximum]=t[i];
}
while(i%maximum!=0)
{
s->data[i%maximum]='$';
i++;
}
}
void DisplayString(BLOCKLINK *h)
{
BLOCKLINK *p;
p=h;
int count=0;
int i=0;
while(p!=NULL)
{
if(i%maximum==0)
{
p=p->next;
if(p==NULL)
break;
printf("->");
}
printf("%c",p->data[i%maximum]);
i++;
}
printf("\n");
}
int main()
{
BLOCKLINK *b1;
char c[maximum];
int i;
gets(c);
printf("初始化块链b1\n");
b1=CreatBLink(c);
DisplayString(b1);
printf("从第6个字符开始,取4个字符,形成新的串d\n");
char d[maximum];
int len=4;
for(i=0;i<len;i++)
d[i]=NULL;
SubStr(b1,d,6,len);
for(i=0;i<StringLength(d);i++)
printf("%c",d[i]);
printf("\n");
printf("从b1的第5个字符开始,用串d替代\n");
Replace(b1,d,5);
DisplayString(b1);
printf("将串d链接到b1之后\n");
StrCon(b1,d);
DisplayString(b1);
printf("b1的长度:");
printf("%d\n",StringlengthBL(b1));
return 0;
}