Day 98スタック構造をリストで実装

2026-06-02 JST ・ 難易度: 中級 ・ カテゴリ: データ構造

Pythonコード

1class Stack:2    def __init__(self):3        self.stack = []4    def push(self, item):5        self.stack.append(item)6    def pop(self):7        if not self.is_empty():8            return self.stack.pop()9        else:10            return None11    def is_empty(self):12        return len(self.stack) == 013    def size(self):14        return len(self.stack)15 16stack = Stack()17while True:18    print("1. プッシュ 2. ポップ 3. サイズ 4. 終了")19    try:20        choice = int(input("選択: "))21    except ValueError:22        print("数字を入力してください")23        continue24    if choice == 1:25        item = input("アイテム: ")26        stack.push(item)27    elif choice == 2:28        item = stack.pop()29        if item is not None:30            print("ポップ: " + item)31        else:32            print("スタックは空です")33    elif choice == 3:34        print("サイズ: " + str(stack.size()))35    elif choice == 4:36        break37    else:38        print("無効な選択")

解説

次に試してみよう