完成数据结构作业,用栈和队列两种方法实现回文;
栈的实现:
include
using namespace std;
constexpr auto MAXSIZE = 50;
typedef struct {
char *base;
char *top;
int stacksize;
}sqStack;
void InitStack(sqStack& s) {
s.base = new char[MAXSIZE];
if (!s.base)
exit(OVERFLOW);
s.top = s.base;
s.stacksize = MAXSIZE;
}
void push(sqStack& s,char e) {
if (s.top - s.base == s.stacksize)
return;
*s.top++ = e;
}
void pop(sqStack& s, char& e) {
if (s.top == s.base)
return;
e = *--s.top;
}
bool isPalindrome(char* str) {
int len = strlen(str);
sqStack S;
InitStack(S);
for (int i = 0; i < len; i++) {
push(S, str[i]);
}
for (int i = 0; i < len; i++) {
char ch;
pop(S,ch);
if (ch != str[i])
return false;
}
return true;
}
int main() {
char s[MAXSIZE];
cin >> s;
if (isPalindrome(s)) {
cout << "字符串" << s << "是回文" << endl;
}
else {
cout << "字符串" << s << "不是回文" << endl;
}
return 0;
}
队列的实现:
include
using namespace std;
constexpr auto MAXSIZE = 50;
typedef struct {
char* base;
int front;
int rear;
}sqQueue;
void InitQueue(sqQueue& q) {
q.base = new char[MAXSIZE];
if (!q.base)
exit(OVERFLOW);
q.front = 0;
q.rear = -1;
}
bool isEmpty(sqQueue &q) {
return q.front > q.rear;
}
bool isFull(sqQueue& q) {
return q.rear == MAXSIZE - 1;
}
bool enqueue(sqQueue& q, char ch) {
if (isFull(q))
return false;
q.base[++q.rear] = ch;
return true;
}
bool dequeue(sqQueue& q, char& ch) {
if (isEmpty(q))
return false;
ch = q.base[q.front++];
return true;
}
bool isPalindrome(char* str) {
int len = strlen(str);
sqQueue Q;
InitQueue(Q);
char stack[MAXSIZE];
int top = -1;
for (int i = 0; i < len; i++) {
enqueue(Q, str[i]);
stack[++top] = str[i];
}
char ch_Q, ch_S;
while (!isEmpty(Q)) {
dequeue(Q, ch_Q);
ch_S = stack[top--];
if (ch_Q != ch_S)
return false;
}
return true;
}
int main() {
char str[MAXSIZE];
cin >> str;
if (isPalindrome(str)) {
cout << "字符串" << str << "是回文" << endl;
}
else {
cout << "字符串" << str << "不是回文" << endl;
}
return 0;
}