Implementing Stack with Python

前端 未结 12 1078
长发绾君心
长发绾君心 2021-01-17 16:16

I am trying to implement a simple stack with Python using arrays. I was wondering if someone could let me know what\'s wrong with my code.

class myStack:
            


        
12条回答
  •  醉梦人生
    2021-01-17 17:05

    Below is my implementation

    class Stack:
        def __init__(self):
            self.items = list()
        def is_empty(self):
            return self.items == []
        def peek(self):
            if self.is_empty():
                print('Cannot peek empty stack')
                return
            else:
                return self.items[-1]
        def pop(self):
            if self.is_empty():
                print('Cannot pop an empty stack')
                return
            else:
                return self.items.pop()
        def size(self):
            return len(self.items)
        def push(self,data):
            self.items.append(data)
    

提交回复
热议问题