高頻算法面試題 2.棧(stack)

定義

只能從尾部加入或刪除, 也就是后進先出(LIFO, last in first out).

棧的方法與實現(xiàn):
push 壓入元素
pop 返回最頂端元素
size 返回棧大小


方法

  • 實現(xiàn)代碼
#LIFO: last item we insert is the first we take out
class Stack:

    #we represent the stack with the help of an array
    def __init__(self):
        self.stack = []
        
    #check whether the stack is empty or not
    def is_empty(self):
        return self.stack == []
        
    #pushing a new item onto the stack - O(1) running time
    #append will put the item at the end of the list
    def push(self, data):
        self.stack.append(data)
        
    #getting the last item we have inserted - O(1) running time
    def pop(self):
    
        #maybe there is no item on the stack
        if self.is_empty():
            raise Exception("Stack is empty...")
    
        data = self.stack[-1]
        del self.stack[-1]
        return data
        
    #getting the last item without removing it
    def peek(self):
    
        #maybe there is no item on the stack
        if self.is_empty():
            raise Exception("Stack is empty...")
    
        return self.stack[-1]
        
    def size_stack(self):
        return len(self.stack)

if __name__ == "__main__":  
        
    stack = Stack()
    
    stack.push(1)
    stack.push(2)
    stack.push(3)
    
    print(stack.size_stack())
    print("Popped: ", stack.pop())
    print("Popped: ", stack.pop())
    print(stack.size_stack())
    print("Peek:", stack.peek())
    print(stack.size_stack())

題目

不存在邊界條件
持續(xù)。。。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容