2 zhangyueaijia zhangyueaijia 于 2013.11.04 11:16 提问

字符串逆置问题,数据结构(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
snowwindice   2013.11.04 22: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;
}

}
链表逆序

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!