2024/10/14日工作总结

完成数据结构作业,用栈和队列两种方法实现回文;
栈的实现:

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;
}

posted @   张黎健  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示