【数据结构】2-1 回文问题
我这种方式其实挺傻的···
相当于是用数组的形式实现了栈的功能
其实完全没有必要
比较回文直接入栈后,不断用栈顶和栈底元素相互比较一下就OK
下面是源代码:(注释部分请自行忽略,主要是直接用栈的功能改过来的)
/*我看见,有星河揉碎在我眼前, 静悄悄化为天上璀璨的云烟,寂静美好。 那时候的天空澄澈,夕阳下的夏日凉风习习, 你抱着吉他,眼里似乎有着通向另一个世界的光。 那时候我们都囿于学业和未可知的未来, 我们唱着跳着,哭着挣扎着,也这样一路前行着……*/ #include<iostream> #include<cstring> using namespace std; struct Node { char word; Node *next; }; class LinkStack { private: Node *top; //Top指针 int number; public: LinkStack(); ~LinkStack(); void Push(char _word); char Pop(); //出栈 char Top(); //取顶部元素 bool Empty(); //判断是否为空栈 void StackTraverse();//打印栈中元素 void filter(); //过滤:空格 void palindromeJudge(); //判断是否为回文 }; void LinkStack::palindromeJudge() { if (number == 0) { cout << "error" << endl; exit(1); } bool flag = true; filter(); char *s = new char[number + 10]; Node *p = top; cout << "这个打印的是栈顶元素" << p->word << endl; for(int i=number-1;i>=0;i--) { s[i] = p->word; p = p->next; } Node *h = top; for (int i = 0; i < number; i++) { if (s[i] != h->word) { flag = false; break; } h = h->next; } if (flag) { StackTraverse(); cout << "是回文" << endl; } else { StackTraverse(); cout << "不是回文" << endl; } } void LinkStack::filter() { if (Empty() == false) { Node *p=top; while (p->next!=NULL) { if (p->word == ' ') { Node *d = p; while (d->next != NULL) { d->word = d->next->word; d = d->next; } d = NULL; number--; } p = p->next; } } } void LinkStack::StackTraverse() { if (Empty()) { cout << "error!" << endl; exit(1); } Node *p = top; while (p!=NULL) { cout << p->word; p = p->next; } cout << endl; } LinkStack::LinkStack() { top = NULL; number = 0; } LinkStack::~LinkStack() { Node *p = top; while (p) { Node *q = p; p = p->next; delete q; } top = NULL; } void LinkStack::Push(char _word) { //top默认为空,所以不需要讨论是否要让最先进去的那个元素的Next为空的情况 Node *s = new Node; s->word = _word; s->next = top; top = s; number++; } char LinkStack::Pop() { char x; if (top == NULL) { cout << "下溢" << endl; exit(1); } x = top->word; Node *p = top; top = top->next; delete p; number--; return x; } char LinkStack::Top() { if (top == NULL) { cout << "下溢" << endl; exit(1); } return top->word; } bool LinkStack::Empty() { return top == NULL; } int main() { LinkStack p; char x[50]; int number; cout << "请输要入栈的语句:"; scanf_s("%[^\n]]", x, 50); number=strnlen_s(x, 50); cout <<"您输入了"<< number << "个字符"<<endl; for (int i = 0; i < number; i++) { p.Push(x[i]); } cout << "打印栈中元素:" << endl; p.StackTraverse(); p.palindromeJudge(); //cout << "出栈功能:" << endl; //cout << p.Pop() << "已完成出栈" << endl; //cout << "打印栈中元素:" << endl; //p.StackTraverse(); //cout << "栈中顶部元素为:" << p.Top() << endl; //cout << "打印栈中元素:" << endl; //p.StackTraverse(); system("pause"); return 0; }