试用C语言写一段以栈为主体的程序,判断依次读入的一个以@为结束符的字母序列,是否为形如‘序列1&序列2’模式的字符序列。其中序列1和序列2中都不含字符‘&’,且序列2是序列1的逆序列。
时间: 2023-04-08 10:05:04 浏览: 38
我可以回答这个问题。以下是一段使用栈来判断字母序列的程序:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_STACK_SIZE 100
typedef struct {
char data[MAX_STACK_SIZE];
int top;
} Stack;
void initStack(Stack *stack) {
stack->top = -1;
}
bool isEmpty(Stack *stack) {
return stack->top == -1;
}
bool isFull(Stack *stack) {
return stack->top == MAX_STACK_SIZE - 1;
}
void push(Stack *stack, char c) {
if (isFull(stack)) {
printf("Stack overflow\n");
exit(EXIT_FAILURE);
}
stack->data[++stack->top] = c;
}
char pop(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack underflow\n");
exit(EXIT_FAILURE);
}
return stack->data[stack->top--];
}
int main() {
Stack stack;
char c;
bool isSequence1 = true;
initStack(&stack);
printf("Enter a sequence of characters terminated by @:\n");
while ((c = getchar()) != '@') {
if (c == '1') {
push(&stack, c);
} else if (c == '0') {
if (isEmpty(&stack)) {
isSequence1 = false;
break;
} else {
pop(&stack);
}
}
}
if (!isEmpty(&stack)) {
isSequence1 = false;
}
if (isSequence1) {
printf("The sequence is of the form 'sequence 1'\n");
} else {
printf("The sequence is not of the form 'sequence 1'\n");
}
return 0;
}