#include <iostream>
using namespace std;
#define MaxSize 5
typedef struct node
{
char data;
struct node* next;
}Lnode,*Snode;
typedef struct linkStack
{
Snode top;
int size;
}linkStack;
void initStack(linkStack*& S) {
S = (linkStack*)malloc(sizeof(linkStack)); //为栈申请两块空间
S->top = (Lnode*)malloc(sizeof(Lnode));
S->top->next = NULL; //初始化头节点和栈大小
S->top = NULL;
S->size = 0;
}
bool pushStack(linkStack* S, char c)
{
Lnode* p = (Lnode*)malloc(sizeof(Lnode));
p->data = c;
p->next = S->top;
S->top = p;
S->size++;
return true;
}
bool popStack(linkStack* S,char& c)
{
if (S->top == NULL) return false;
Snode p = S->top;
c = p->data;
S->top = S->top->next;
free(p);
S->size--;
return true;
}
int scanfArr(char arr[])
{
char c;
int len = 0;
for(int i = 0; i < MaxSize; i++)
{
cin >> c;
if (c == '*') break;
arr[i] = c;
len++;
}
return len;
}
bool is_palindrome_number(linkStack*& S, char arr[], int length)
{
initStack(S); //初始化栈
// 将数组前半段入栈, 若length为奇数, 则向下取整
for (int i = 0; i < length / 2; i++) {
pushStack(S, arr[i]);
}
// 判断数组奇偶性
int start; // 字符比较的起始位置
// 若数组为偶数
if (length % 2 == 0) {
start = length / 2;
}
// 若数组为奇数
else {
start = length / 2 + 1;
}
// 回文数判断
for (int i = start; i < length; i++) {
char c;
popStack(S, c);
// 若出栈的字符与arr[i]不等
if (c != arr[i]) {
return false;
}
}
return true;
}
int main()
{
linkStack* S;
char arr[MaxSize];
int length = scanfArr(arr);
if (is_palindrome_number(S, arr, length)) {
cout << "这个数组是一个回文串" << endl;
}
else {
cout << "这个数组不是一个回文串" << endl;
}
return 0;
}
c++栈实现回文串
最新推荐文章于 2023-11-12 19:32:52 发布