Implementing Stack with Python

前端 未结 12 1088
长发绾君心
长发绾君心 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:06

    Below is the simple implementation of stack in python. In addition, it returns the middle element at any point in time.

      class Stack:
            def __init__(self):
                self.arrList = []
    
            def isEmpty(self):
                if len(self.arrList):
                    return False
                else:
                    return True
    
            def push(self, val):
                self.arrList.append(val)
    
            def pop(self):
                if not self.isEmpty():
                    self.arrList[len(self.arrList)-1]
                    self.arrList = self.arrList[:len(self.arrList)-1]
                else:
                    print "Stack is empty"
    
            def returnMiddle(self):
                if not self.isEmpty():
                    mid = len(self.arrList)/2
                    return self.arrList[mid]
                else:
                    print "Stack is empty"
    
            def listStack(self):
                print self.arrList
    
        s = Stack()
        s.push(5)
        s.push(6)
        s.listStack()
        print s.returnMiddle()
        s.pop()
        s.listStack()
        s.push(20)
        s.push(45)
        s.push(435)
        s.push(35)
        s.listStack()
        print s.returnMiddle()
        s.pop()
        s.listStack()
    

    Output:

    [5, 6]
    6
    [5]
    [5, 20, 45, 435, 35]
    45
    [5, 20, 45, 435]
    

提交回复
热议问题