// Jin
// 2020-08-27
// 单链表check回文
#include
using namespace std;
typedef struct A {
char a;
struct A* next;
}Linklist;
A* newA(char ch, A* nt){
A *ob = new A;
ob->a = ch;
ob->next = nt;
return ob;
}
A* reserve(A* ob) {
if(ob == NULL || ob->next == NULL) {
return ob;
}
A* tmp1 = ob;
A* tmp2 = ob->next;
while(tmp2->next != NULL) {
A* tmp3 = tmp2->next;
tmp2->next = tmp1;
tmp1 = tmp2;
tmp2 = tmp3;
}
tmp2->next = tmp1;
tmp1->next = NULL;
return tmp2;
}
//判断回文
bool checkBackStr(A* st){
A* oneA = st;
A* twoA = st;
if (st == NULL) {
return false;
}
if (st->next == NULL){
return true;
}
int i = 1;
int j = 1;
bool even = true;
//分别标记走1步和2步的指针位置,直到走两步的走到头;
while(twoA != NULL){
cout<<"Debug "<<i<<"th ch is “<< oneA->a<<” next “<<j<<” th "<a<<endl;
j++;
twoA = twoA->next;
if(twoA == NULL){
even = false;
break;
}
j++;
i++;
oneA = oneA->next;
twoA = twoA->next;
}
cout<<"Middle "<<i<<"th ch is "<< oneA->a<<endl;
//单个字符
if(oneA->next == NULL){
return true;
}
//奇数个字符,跳过一个
if(!even){
oneA=oneA->next;
}
// 从中间位置检测 “1234 -- 4321”
// 逆序对比
A* p = reserve(oneA);
while(p != NULL ) {
if(p->a != st->a){
return false;
}
p= p->next;
st = st->next;
}
return true;
}
int main() {
cout << “hello Link” << endl;
A* a = NULL;
a = newA(‘a’,NULL);
a = newA(‘b’,a);
a = newA(‘c’,a);
a = newA(‘1’,a);
a = newA(‘c’,a);
a = newA(‘b’,a);
a = newA(‘a’,a);
//a = newA(‘c’,a);
//a = newA(‘b’,a);
//a = newA(‘a’,b);
int i =0;
for(A* t=a;t !=NULL; t=t->next){
i++;
cout<<i<<"th "<<t->a<<endl;
}
cout<<(checkBackStr(a))<<endl;
return 0;
}