栈:给定嗹入栈嗴列和嗹嗰栈嗴列,判断嗵嗰栈嗴列是否合法,代码用C语言
时间: 2023-07-09 08:17:09 浏览: 69
可以使用C语言来实现这个算法,以下是代码实现:
```c
#include <stdio.h>
#include <stdbool.h>
#define MAX_SIZE 100
bool is_valid_stack_sequence(int push_seq[], int push_len, int pop_seq[], int pop_len) {
int stack[MAX_SIZE], top = -1;
int pop_index = 0;
for (int i = 0; i < push_len; i++) {
stack[++top] = push_seq[i];
while (top >= 0 && stack[top] == pop_seq[pop_index]) {
top--;
pop_index++;
}
}
return top == -1 && pop_index == pop_len;
}
int main() {
int push_seq[] = {1, 2, 3, 4, 5};
int pop_seq[] = {4, 5, 3, 2, 1};
int push_len = sizeof(push_seq) / sizeof(push_seq[0]);
int pop_len = sizeof(pop_seq) / sizeof(pop_seq[0]);
if (is_valid_stack_sequence(push_seq, push_len, pop_seq, pop_len)) {
printf("The pop sequence is valid.\n");
} else {
printf("The pop sequence is invalid.\n");
}
return 0;
}
```
其中,push_seq 和 pop_seq 分别为入栈序列和出栈序列,push_len 和 pop_len 分别为它们的长度。函数返回一个布尔值,表示出栈序列是否合法。
阅读全文