HuiWen.cpp #include "stdio.h" #include "string.h" #define MaxQueueSize 100 #define MaxStackSize 100 typedef char DataType; #include "SeqCQueue.h" #include "SeqStack.h" void HuiWen(char str[]) { SeqCQueue myQueue; SeqStack myStack; char x, y; int i, length; length = strlen(str); QueueInitiate(&myQueue); StackInitiate(&myStack); for (i = 0; i < length; i++) { QueueAppend(&myQueue, str[i]); StackPush(&myStack, str[i]); } while(QueueNotEmpty(&myQueue) ==1 && StackNotEmpty(&myStack) ==1) { if (QueueDelete(&myQueue, &x) ==1 && StackPop(&myStack, &y) && x != y) { printf("%s 不是回文!/n", str); return; } } if (QueueNotEmpty(&myQueue) || StackNotEmpty(&myStack)) { printf("%s不是回文!/n", str); } else { printf("%s是回文!/n", str); } } void main() { char str[100]; while(scanf("%s", &str) != EOF) { HuiWen(str); //不能用&str } } SeqCQueue.h #include "stdio.h" #include "string.h" typedef struct { DataType queue[MaxQueueSize]; int rear; int front; int count; } SeqCQueue; void QueueInitiate(SeqCQueue * Q) { Q->rear = 0; Q->front = 0; Q->count = 0; } int QueueNotEmpty(SeqCQueue * Q) { if (Q->count != 0) { return 1; } else { return 0; } } int QueueAppend(SeqCQueue * Q, DataType x) { if (Q->count > 0 && Q->rear == Q->front) { printf("队列已满无法插入!/n"); return 0; } else { Q->queue[Q->rear] = x; //队尾相当于空指针 Q->rear = (Q->rear + 1) % MaxQueueSize; Q->count++; return 1; } } int QueueDelete(SeqCQueue * Q, DataType *d) { if (Q->count == 0) { printf("队列已经空了!/n"); return 0; } else { *d = Q->queue[Q->front]; Q->front = (Q->front + 1) % MaxQueueSize; //只需要对头+1就可以了,并不需要删除 Q->count--; return 1; } } int QueueGet(SeqCQueue * Q, DataType *d) { if (Q->count == 0) { printf("队列已经空了!无元素可以取/n"); return 0; } else { *d = Q->queue[Q->front]; return 1; } } SeqStack.h #include "stdio.h" #include "math.h" typedef struct { DataType stack [MaxStackSize]; int top; } SeqStack; void StackInitiate(SeqStack *S) { S->top = 0; } int StackNotEmpty(SeqStack *S) { if (S->top <= 0) { return 0; } else { return 1; } } int StackPush(SeqStack * S,DataType x) { if (S->top >= MaxStackSize) { printf("堆栈已满无法插入!/n"); return 0; } else { //这时候S->top刚好为空待插入,因为数组从0开始 S->stack [S->top] = x; S->top++; return 1; } } int StackPop(SeqStack * S, DataType *d) { if ( S->top <= 0) { printf("堆栈已经空无需出栈!/n"); return 0; } else { //记住顺序,因为数组是从0开始的 S->top--; *d = S->stack [S->top]; return 1; } } int StackTop(SeqStack * S, DataType *d) { if ( S->top <= 0) { printf("堆栈已经空,没有数可以取出!/n"); return 0; } else { *d = S->stack [S->top-1]; return 1; } }