问题描述
试写一个算法,判断依次读入的一个以@为结束符的字母序列,是否为形如'序列1&序列2'模式的字符序列。其中序列1和序列2中都不含字符‘&’,且序列2是序列1的逆序列。例如,‘a+b&b+a’是属于该模式的字符序列,而'1+3&3-1'则不是。
解题思路
首先将字符串以&为分割点,分割成两部分,前一部分存入栈中,后一部分存入队列,而后分别出栈、出队,判断出栈、出队的元素是否一致,如果一致,则是回文数,否则不是回文数。
代码实现
#include
#include
#include
#define MAXSIZE 51
#define FALSE 0
#define TRUE 1
typedef struct Stack {
char elem[MAXSIZE];
int top;
} Stack, *SeqStack;
/*队列的数据结构*/
typedef struct Queue {
char data;
struct Queue *next;
} Queue;
typedef struct LinkQueue {
Queue *front;
Queue *rear;
} LinkQueue;
/*栈操作*/
void initStack(SeqStack stack);
int emptyStack(SeqStack stack);
int fullStack(SeqStack stack);
int push(SeqStack stack, char element);
int pop(SeqStack stack, char *element);
/*队列操作*/
int initQueue(LinkQueue *queue);
int enterQueue(LinkQueue *queue, char x);
int deleteQueue(LinkQueue *queue, char *x);
int main(int argc, char *argv[]) {
SeqStack stack;
stack = (SeqStack)malloc(sizeof(Stack));
initStack(stack);
LinkQueue queue;
initQueue(&queue);
char datas[MAXSIZE];
gets(datas);
int i = 0;
int flag = 1;
while(datas[i] != '@') {
if (datas[i] == '&') {
flag = 0;
i++;
continue;
}
if (flag) {
push(stack, datas[i++]);
} else {
enterQueue(&queue, datas[i++]);
}
}
char stack1, queue1;
while (pop(stack, &stack1) && deleteQueue(&queue, &queue1)) {
if (stack1 != queue1) {
flag = 1;
break;
}
}
if (flag) {
printf("不是回文数!\n");
} else {
printf("是回文数!\n");
}
return 0;
}
/**
* 初始化一个空栈
*/
void initStack(SeqStack stack) {
stack->top = -1;
}
/**
* 判断栈是否为空
*/
int emptyStack(SeqStack stack) {
int result = 0;
if (stack->top == -1) {
result = 1;
}
return result;
}
/**
* 判断栈是否已满
*/
int fullStack(SeqStack stack) {
int result = 0;
if (stack->top == MAXSIZE - 1) {
result = 1;
}
return result;
}
/**
* 入栈操作
*/
int push(SeqStack stack, char element) {
if (fullStack(stack)) {
printf("栈已满!\n");
return -1;
}
stack->top++;
stack->elem[stack->top] = element;
return 1;
}
/**
* 出栈操作
*/
int pop(SeqStack stack, char *element) {
if (emptyStack(stack)) {
return FALSE;
}
*element = stack->elem[stack->top];
stack->top--;
return TRUE;
}
/**
* 初始化队列
*/
int initQueue(LinkQueue *queue) {
queue->front = (Queue*)malloc(sizeof(Queue));
if (queue->front != NULL) {
queue->rear = queue->front;
queue->front->next = NULL;
return TRUE;
} else {
return FALSE;
}
}
/**
* 入队操作
*/
int enterQueue(LinkQueue *queue, char x) {
Queue *newQueue;
newQueue = (Queue*)malloc(sizeof(Queue));
if (newQueue != NULL) {
newQueue->data = x;
newQueue->next = NULL;
queue->rear->next = newQueue;
queue->rear = newQueue;
return TRUE;
} else {
return FALSE;
}
}
/**
* 出队操作
*/
int deleteQueue(LinkQueue *queue, char *x) {
Queue *p;
if (queue->front == queue->rear) {
return FALSE;
}
p = queue->front->next;
queue->front->next = p->next;
if(queue->rear == p) {
queue->rear = queue->front;
}
*x = p->data;
free(p);
return TRUE;
}
运行结果