eolymp
bolt
Спробуйте наш новий інтерфейс для відправки розв'язків
Задачі

Стек необмеженого розміру

опубліковано 04.01.24, 21:09:41

include <bits/stdc++.h>

using namespace std; using ll = long long;

int main() { iosbase::syncwith_stdio(0); cin.tie(0); string s; stack<int> st; int x; while(cin >> s){ if(s == "exit"){ cout << "bye"; return 0; } if(s == "push"){ cin >> x; st.push(x); cout << "ok"; } if(s == "pop"){ if(st.empty()) cout << "error"; else { cout << st.top(); st.pop(); } } if(s == "back"){ if(st.empty()) cout << "error"; else cout << st.top(); } if(s == "size"){ cout << st.size(); } if(s == "clear"){ while(!st.empty()) st.pop(); cout << "ok"; } cout << endl; } }

опубліковано 03.04.24, 02:19:09

import java.util.*;

public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); MyStack stack = new MyStack();

    while (scanner.hasNextLine()) {
        String command = scanner.nextLine();

        if (command.startsWith("push")) {
            int num = Integer.parseInt(command.substring(5));
            stack.push(num);
            System.out.println("ok");
        } else if (command.equals("pop")) {
            try {
                System.out.println(stack.pop());
            } catch (EmptyStackException e) {
                System.out.println("error");
            }
        } else if (command.equals("back")) {
            try {
                System.out.println(stack.peek());
            } catch (EmptyStackException e) {
                System.out.println("error");
            }
        } else if (command.equals("size")) {
            System.out.println(stack.size());
        } else if (command.equals("clear")) {
            stack.clear();
            System.out.println("ok");
        } else if (command.equals("exit")) {
            System.out.println("bye");
            break;
        }
    }
}

static class MyStack {
    private List<Integer> stack;

    public MyStack() {
        stack = new ArrayList<>();
    }

    public void push(int num) {
        stack.add(num);
    }

    public int pop() {
        if (stack.isEmpty()) {
            throw new EmptyStackException();
        }
        int lastIndex = stack.size() - 1;
        int lastElement = stack.get(lastIndex);
        stack.remove(lastIndex);
        return lastElement;
    }

    public int peek() {
        if (stack.isEmpty()) {
            throw new EmptyStackException();
        }
        return stack.get(stack.size() - 1);
    }

    public int size() {
        return stack.size();
    }

    public void clear() {
        stack.clear();
    }
}

}