mirror of
https://github.com/ParkMoonJ/KaoYan.git
synced 2026-11-01 13:25:21 +08:00
Update 3 栈和队列.md
This commit is contained in:
@@ -324,8 +324,63 @@ PPPPLRRL // 1432 输入受限
|
||||
|
||||
### 3.18 试写一个判别表达式中开、闭括号是否配对出现的算法。
|
||||
|
||||
```cpp
|
||||
bool bracket(char a) {
|
||||
Stack S;
|
||||
char x;
|
||||
|
||||
InitStack(S);
|
||||
for (int i = 0; a[i]; i++) {
|
||||
switch (a[i]) {
|
||||
case ']':
|
||||
pop(S, x);
|
||||
if (x != '[') {
|
||||
return false;
|
||||
}
|
||||
case ')':
|
||||
pop(S, x);
|
||||
if (x !- '(') {
|
||||
return false;
|
||||
}
|
||||
default:
|
||||
push(S, a[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3.19 假设一个算术表达式中可以包含三种括号:圆括号 $($ 和 $)$、方括号 $[$ 和 $]$ 和花括号 $\{$ 和 $\}$,且这三种括号可按任意的次序嵌套使用(如:$\cdots [\cdots \{\cdots\} \cdots [\cdots] \cdots]\cdots [\cdots] \cdots (\cdots) \cdots$)。编写判别给定表达式中所含括号是否正确配对出现的算法(已知表达式已存入数据元素为字符的顺序表中)。
|
||||
|
||||
```cpp
|
||||
bool bracket(char a) {
|
||||
Stack S;
|
||||
char x;
|
||||
|
||||
InitStack(S);
|
||||
for (int i = 0; a[i]; i++) {
|
||||
switch (a[i]) {
|
||||
case ']':
|
||||
pop(S, x);
|
||||
if (x != '[') {
|
||||
return false;
|
||||
}
|
||||
case ')':
|
||||
pop(S, x);
|
||||
if (x != '(') {
|
||||
return false;
|
||||
}
|
||||
case '}':
|
||||
pop(S, x);
|
||||
if (x != '{') {
|
||||
return false;
|
||||
}
|
||||
default:
|
||||
push(S, a[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 3.20 假设以二维数组 $g(1 \cdots m, 1 \cdots n)$ 表示一个图像区域,$g[i, j]$ 表示该区域中点 $(i, j)$ 所具颜色,其值为从 $0$ 到 $k$ 的整数。编写算法置换点 $(i_0, j_0)$ 所在区域的颜色。约定和 $(i_0, j_0)$ 同色的上、下、左、右的邻接点为同色区域的点。
|
||||
|
||||
### 3.21 假设表达式由单字母变量和双目四则运算算符构成。试写一个算法,将一个通常书写形式且书写正确的表达式转换为逆波兰式。
|
||||
@@ -408,7 +463,8 @@ int akm(int m, int n) {
|
||||
if (!n) {
|
||||
akm(m - 1, 1);
|
||||
} else {
|
||||
akm(m - 1, akm(m , n - 1));
|
||||
tmp = akm(m, n - 1);
|
||||
akm(m - 1, tmp);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -417,7 +473,9 @@ int akm(int m, int n) {
|
||||
#### (2)写出非递归算法;
|
||||
|
||||
```cpp
|
||||
int akm(int m, int n) {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
#### (3)根据非递归算法,画出求 $akm(2, 1)$ 时栈的变化过程。
|
||||
|
||||
Reference in New Issue
Block a user