|
发表于 2022-4-26 11:58:08
|
显示全部楼层
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- #include <stdbool.h>
- #define STACK_INIT_SIZE 20
- #define STACKINCREMENT 10
- typedef char ElemType;
- typedef struct
- {
- ElemType *base;
- ElemType *top;
- int stackSize;
- }sqStack;
- void InitStack(sqStack *s)
- {
- s->base = malloc(STACK_INIT_SIZE * sizeof(ElemType));
- if( !s->base )
- {
- exit(0);
- }
- s->top = s->base;
- s->stackSize = STACK_INIT_SIZE;
- }
- void Push(sqStack *s, ElemType e)
- {
- if( s->top - s->base >= s->stackSize )
- {
- s->base = (ElemType *)realloc(s->base, (s->stackSize += STACKINCREMENT) * sizeof(ElemType));
- //s->base = (ElemType *)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(ElemType));
- if( !s->base )
- {
- exit(0);
- }
- }
- *(s->top) = e;
- s->top++;
- }
- void Pop(sqStack *s, ElemType *e)
- {
- if( s->top == s->base )
- {
- return;
- }
- *e = *--(s->top);
- }
- int StackLen(sqStack s)
- {
- return (s.top - s.base);
- }
- void stack_deinit(sqStack *s) {
- if(s) free(s->base);
- }
- //void main()
- int main(void)
- {
- sqStack s;
- InitStack(&s);
- while(1) {
- char ch = getchar();
- if(ch == '@') break;
- Push(&s, ch);
- }
- char buff[StackLen(s)];
- size_t size = 0;
- while(StackLen(s) != 0) {
- char e; Pop(&s, &e);
- buff[size++] = e;
- }
- for(size_t i = 0; i < size; ++i) {
- Push(&s, buff[i]);
- }
- bool flag = true;
- for(size_t i = 0; i < size; ++i) {
- char e; Pop(&s, &e);
- if(e != buff[i]) {
- flag = false;
- break;
- }
- }
- printf("%s\n", flag ? "==" : "!=");
- stack_deinit(&s);
- return 0;
- #if 0
- char a[STACK_INIT_SIZE];
- char b[STACK_INIT_SIZE];
- int i,j = 0;
- int len;
- sqStack Pal1,Pal2;
- ElemType c;
- InitStack(&Pal1);
- InitStack(&Pal2);
-
- printf("请输入一组以@结尾的回文:");
- scanf("%c", &c);
- while( c != '@' )
- {
- Push(&Pal1, c);
- scanf("%c", &c);
- }
- getchar();
-
- len = StackLen(Pal1);
- printf("栈的当前容量是: %d\n", len);
- printf("第一个栈为:");
- for( i=0; i < len; i++ )
- {
- Pop(&Pal1, &c);
- printf("%c",c);
- }
- for( i=0; i < len-1; i++ )
- {
- Pop(&Pal1, &c);
- Push(&Pal2, c);
- }
- printf("\n");
- printf("第二个栈为:");
- for( i=0; i < len; i++ )
- {
- Pop(&Pal2, &c);
- printf("%c",c);
- }
-
- printf("\n");
- for( i=0; i < len-1; i++ )
- {
- Pop(&Pal1, &c);
- a = c;
- }
- printf("第一个数组为");
- for( i=0; i < len; i++ )
- {
- printf("%c ",a);
- }
- printf("\n");
- for( i=0; i < len; i++ )
- {
- Pop(&Pal2, &c);
- b = c;
- }
- printf("第二个数组为:");
- for( i=0; i < len; i++ )
- {
- printf("%c ",b);
- }
- printf("\n");
- printf("比较数组:");
- for( i=0; i < len-1; i++ )
- {
- if(a == b)
- {
- j++;
- printf("%c-%c %d %d\n ",a,b,j,i);
- }
- }
- if(j == len)
- {
- printf("是回文");
- }
- else
- {
- printf("不是回文");
- }
- return 0;
- #endif
- }
复制代码 |
|