入栈和出栈的基本操作

入栈和出栈的基本操作,输入-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]);
                }
            }
        }
    }
}
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值