【问题描述】
从txt文件输入一个整数序列a1,a2,a3,……,an,试编写算法实现,用栈结构存储输入的整数,当ai!=-1时,将ai进栈,当ai=-1时,使用txt文件输出栈顶整数并出栈,栈空间为20,算法应对异常情况时输出错误信息(栈满输出999、栈空下溢输出-999等)。
【类库使用要求】不允许使用STL中的容器类,比如stack、vector、list等,栈的操作需要自行编写代码。
【输入形式】
文件输入,文件名为in.txt
【输出形式】文件输出,文件名为out.txt
【样例输入1】
1 2 3 -1 -1 -1 -1
【样例输出1】
3
2
1
-999
【样例输入2】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1
【样例输出2】
999
【样例输入3】
1 2 3 4 -1 -1 -1 4 5 -1
【样例输出3】
4
3
2
5
分析:
使用栈处理此问题,栈类实现三个方法及一个构造函数。
实现:
push()
pop()
isEmpty()
Stack()
class Stack {
int top;
int arr[200];
public:
Stack() { top = -1; }
bool push(int x);
int pop();
bool isEmpty();
};
bool Stack::push(int x) {
if (top >= 19) {
return false;
}
else {
arr[++top] = x;
return true;
}
}
int Stack::pop() {
if (top < 0) {
return -999;
}
else {
int x = arr[top--];
return x;
}
}
bool Stack::isEmpty() {
return (top < 0);
}
int main() {
Stack s;
ifstream infile("in.txt");
ofstream outfile("out.txt");
int x;
bool hasPrinted = false;
//读取整数直到文件结束
while (infile >> x) {
// 如果读取的不是-1
if (x != -1) {
// 压入
if (!s.push(x)) {
outfile << "999" << endl;
}
// 栈空更新
hasPrinted = false;
}
// 如果读取-1
else {
// 弹出元素
int popped = s.pop();
// 如果已经下溢则报错,继续循环
if (popped == -999 && hasPrinted) {
continue;
}
// 弹出元素输出到output
outfile << popped << endl;
if (popped == -999) {
hasPrinted = true;
}
}
}
infile.close();
outfile.close();
return 0;
}