icefox_ 2013-11-04 03:16 采纳率: 100%
浏览 3109
已采纳

字符串逆置问题,数据结构(C++)

#include
#include
using namespace std;

typedef struct chunk
{
char ch;
struct chunk *next;
};
typedef struct LString
{
chunk *head,*tail;
int curlen;
};

//创建串的函数
string CreateString(LString &S)
{
cout<<"请输入串:"< string s1;
S.head = new chunk;
chunk *tem_chunk;
tem_chunk = S.head;
tem_chunk->next = new chunk;
tem_chunk = tem_chunk->next;
getline(cin,s1);
for(int i = 0;i < s1.length();i++)
{
tem_chunk->ch = s1[i] ;
tem_chunk->next = new chunk;
tem_chunk = tem_chunk->next;
}
return s1;
}

//显示串的函数
void ShowString(LString S,string s1)
{
chunk *tem = S.head;
for(int i = 0 ; i < s1.length() ; i++)
{

tem = tem->next;
cout<ch;
}

}

//匹配函数
int Index(string S,string T){
int i=0,j=0,n,m;
n=S.length();
m=T.length();
while(i<n&&j<m){
if(S[i]==T[j]){
i++;
j++;
}
else{
i=i-j+1;
j=0;
}
}
if(j==m)
{
cout<<"匹配成功"<<endl;
return i-m+1;
}
else
{
cout<<"匹配不成功"<<endl;
return 0;
}

}

//逆置函数
void Inverse(LString &S,LString T,int i,int k) //i为逆置起始点,k为子串长度
{
chunk *tem1 ,*tem2,*tem;
tem1 = S.head ;
//
for(int j = 0; j < i ;j++)
tem1 = tem1->next;
//
tem2 = tem1->next;
for(int j = 0; j< k*k ; j++)
{
tem = tem2->next ;
tem1->next = tem;
tem2->next = tem1;
tem1 = tem2;
tem2 = tem;
}

}
int main()
{
//完成匹配两个串,并且找到首次匹配的子串并且逆置
LString S,T;
string s1,s2;
s1 = CreateString(S) ;
s2 = CreateString(T);
int n = Index(s1,s2);
if(n!=0)
{
Inverse(S,T,n,s2.length());
cout<<"逆置后字符串:";
ShowString(S,s1);
}
return 0;
}

一直抱错,我调试了之后显示就是在逆置函数那个地方出错了
哪位好心的大神帮忙解答一下,字符串逆置我都搞晕了~~~

要求达到的效果是

S:ABCDEFGH T:CDEF
逆置后: S:ABFEDCGH

  • 写回答

1条回答

  • snowwindice 2013-11-04 14:40
    关注

    //逆置函数
    void Inverse(LString &S,LString T,int i,int k) //i为逆置起始点,k为子串长度
    {
    if(k==1)
    return;

    chunk *tem1 ,*tem2,*tem3;
    chunk *begin , *end;
    tem1 = S.head ;
    //
    for(int j = 0; j < i-1 ;j++)
        begin = tem1->next;
    tem1 = begin->next;
    tem2 = tem1->next;
    if(k==2)
    {
        begin->next = tem2;
        end = tem2->next;
        tem2->next = tem1;
        tem1->next = end;
    }
    else
    {
        chunk *tem1_cpy = tem1;//记录起始位置,最后要执行tem1_cpy->next = end
        tem3 = tem2->next;
        for(int i = 0; i<k-2; i++)
        {
            tem2->next =tem1;
            tem1 = tem2;
            tem2 = tem3;
            tem3 = tem3->next;
        }
        tem2->next = tem1;
        begin->next = tem2;
        tem1_cpy->next = tem3;
    }
    

    }
    链表逆序

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)