Menu
CoddyTech

empty

Pelajaran 8 dari 13 dalam kursus Stack, Seri Struktur Data #1 di Coddy.

challenge icon

Tantangan

Mudah

Tambahkan method bernama empty ke Stack yang tidak menerima argumen dan mengembalikan true jika stack kosong, jika tidak, mengembalikan false.

Coba sendiri

#include <iostream>
#include <sstream>
#include <string>
#include "stack.h"

int main() {
    Stack stack;
    std::string line;
    while (std::getline(std::cin, line)) {
        std::istringstream iss(line);
        std::string cmd;
        if (!(iss >> cmd)) continue;
        if (cmd == "push") {
            int x; iss >> x; stack.push(x);
        }
        else if (cmd == "top") {
            std::cout << stack.top() << std::endl;
        }
        else if (cmd == "pop") {
            std::cout << stack.pop() << std::endl;
        }
        else if (cmd == "size") {
            std::cout << stack.size() << std::endl;
        }
        else if (cmd == "empty") {
            std::cout << (stack.empty() ? "true" : "false") << std::endl;
        }
    }
    return 0;
}

Semua pelajaran di Stack, Seri Struktur Data #1

Latihan sendiri: Compiler C online