typedef int T; // 数据元素的数据类型
struct Stack{
T* data; // 数据元素存储空间的开始地址
int top; // 栈顶元素所处数组位置
int max; // 栈存储空间最多可存储的数据元素个数
};
bool Stack_IsEmpty(Stack* stk)
// 判断栈是否空
{
return -1 == stk->top;
}
Stack* Stack_Create(int maxlen)
// 创建栈
{
Stack* stk = (Stack*)malloc(sizeof(Stack));
stk->data = (T*)malloc(sizeof(T)*maxlen);
stk->max = maxlen;
stk->top = -1;
return stk;
}
T Stack_Push(Stack* stk, T e)
// 将元素e压入栈顶
// 返回栈顶点元素
{
if(Stack_IsFull(stk)) {
printf("Stack_IsFull(): stack full error when push element to the stack!\n");
Stack_Free(stk);
exit(0);
}
else{
stk->top += 1;
stk->data[stk->top] = e;
return Stack_Top(stk);
}
}
T Stack_Pop(Stack* stk)
// 将栈顶元素出栈
// 返回栈顶元素
{
if(Stack_IsEmpty(stk)) {
printf("Stack_IsEmpty(): stack empty error when pop element of the stack top!\n");
Stack_Free(stk);
exit(0);
}
else{
T topE = Stack_Top(stk);
stk->top -= 1;
return topE;
}
}
void Palindrome(T* str, int len)
// 利用stack栈判断字符串是否为回文串
// 输入参数:字符串序列,字符串长度
// 若是回文串输出YES,否则输出NO,末尾换行
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
Stack *stk = Stack_Create(100);//创建一个栈
int i;
for(i=0;i<len/2;i++)
Stack_Push(stk, str[i]);//将前len/2个字符存进栈里
int state = 1; //设置标志
if(len%2==1) //len为奇数
i++;
for(;i<len&&state;i++)
if(!Stack_IsEmpty(stk)&&Stack_Top(stk) == str[i])//栈不空及栈顶元素与str[i]??相等
Stack_Pop(stk);//将元素从栈中弹出
else//遇到不符合,结束循环
state=0;
if(Stack_IsEmpty(stk)&&state)//栈空及标志为1
printf("YES");
else
printf("NO");
printf("\n");
/********** End **********/
}
思路:
- 将前len/2个字符放进栈中
- 设置标志
- 将栈顶元素与str中对称位置元素进行比较
- 若相同,栈顶元素弹栈,进行下一次比较
- 若不同,标志设为0,结束循环
我出现的错误:
进行以下操作时`
for(;i<len&&state;i++)
if(!Stack_IsEmpty(stk)&&Stack_Top(stk) == str[i])//栈不空及栈顶元素与str[i]??相等
Stack_Pop(stk);//将元素从栈中弹出
else//遇到不符合,结束循环
state=0;
误以为入栈操作后,i=len/2-1,而实际上,入栈出循环的条件是i=len/2
所以与栈顶元素比较的是str[i]