入栈和出栈的基本操作,输入-1表示出栈,否则入栈,出栈若失败输出error并退出本轮循环。
输入样例:
5
1 2 -1 -1 1
5
1 -1 -1 2 2
0
输出样例:
2
1
1
error
C
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MaxSize 100
typedef struct SqStack {
int data[MaxSize];
int top;
} SqStack;
void stackInit(SqStack *stack);
bool stackEmpty(SqStack stack);
bool stackPush(SqStack *stack, int e);
bool stackPop(SqStack *stack, int *x);
int main() {
int m;
while (scanf("%d%*c", &m) && m != 0) {
int *buffer = (int *) calloc(m, sizeof(int));
SqStack stack;
int c;
stackInit(&stack);
for (int i = 0; i < m; i++) {
scanf("%d%*c", buffer + i);
}
for (int i = 0; i < m; i++) {
if (buffer[i] == -1) {//进行出栈操作
if (stackPop(&stack, &c)) {//出栈成功
printf("%d\n", c);
} else {//出栈失败
printf("error\n");
break;
}
} else {//进行入栈操作
stackPush(&stack, buffer[i]);
}
}
free(buffer);
}
return 0;
}
void stackInit(SqStack *stack) {
stack->top = -1;
}
bool stackEmpty(SqStack stack) {
return stack.top == -1 ? true : false;
}
bool stackPush(SqStack *stack, int e) {
if (stack->top == MaxSize - 1) return false;
stack->data[++stack->top] = e;
return true;
}
bool stackPop(SqStack *stack, int *x) {
if (stackEmpty(*stack)) return false;
*x = stack->data[stack->top--];
return true;
}
Java
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
int len = scanner.nextInt();
int[] arr = new int[len];
Stack<Integer> stack = new Stack<>();
if (len == 0) break;
for (int i = 0; i < len; i++) {
arr[i] = scanner.nextInt();
}
/*System.out.println(Arrays.toString(arr));*/
for (int i = 0; i < len; i++) {
if (arr[i] == -1) {
try {
System.out.println(stack.pop());
} catch (Exception e) {
System.out.println("error");
break;
}
} else {
stack.push(arr[i]);
}
}
}
}
}