iT邦幫忙

2023 iThome 鐵人賽

DAY 7
0

Stack堆疊, 顧名思義其資料結構猶如堆疊般,最先放進去的資料最後才能取得(First-in last-out, FILO),最後放進去的資料,可以最先取得(Last-In First-Out manner, LIFO),這裡給大家展示用三種表現stack的方法,分別使用python list(without size limit)、python list(with size limit)和linked list (without size limit)。
https://ithelp.ithome.com.tw/upload/images/20230918/20162172BxE7OvdUvU.png
python list (without size limit)

class Stack:
    def __init__(self):
        self.list=[]
    def __str__(self):
        values=[str(x) for x in self.list[::-1]]
        return '\n'.join(values)
    
    # isEmpty: 時間複雜度:O(1),空間複雜度:O(1)
    def isEmpty(self):
        if self.list==[]:
            return True
        else:
            return False
        
    # push: 時間複雜度:O(1),空間複雜度:O(1)
    def push(self,value):
        self.list.append(value)
        return 'The element is successfully inserted'
    
    # pop: 時間複雜度:O(1),空間複雜度:O(1)
    def pop(self):
        if self.isEmpty():
            return 'There is no element in the stack'
        else:
            return self.list.pop()
        
    # 最上層的資料: 時間複雜度:O(1),空間複雜度:O(1)
    def peek(self):
        if self.isEmpty():
            return 'There is no element in the stack'
        else:
            return self.list[(len(self.list)-1)]
    # 刪除整個stack: 時間複雜度:O(1),空間複雜度:O(1)
    def delete(self):
        self.list=None
        
mystack=Stack()
mystack.isEmpty()
>>True

mystack.push(5)
mystack.push(2)
mystack.push(3)
print(mystack)
>> 3
   2
   5
mystack.pop()
>> 3
print(mystack)
>> 2
   5
mystack.peek()
>> 2
print(mystack)
>> 2
   5

用python list (with size limited)製作stack

class stack:
    
    # 時間複雜度: O(1), 空間複雜度:O(N)
    def __init__(self,size):
        self.list=[None]*size
        self.maxsize=size
        self.top=-1
    
    # 時間複雜度: O(N), 空間複雜度:O(1)    
    def __str__(self):
        values=[str(x) for x in self.list[::-1]]
        return '\n'.join(values)
    
    # 時間複雜度: O(1), 空間複雜度:O(1)  
    def isFull(self):
        if self.top>=self.maxsize-1:
            return True
        else:
            return False
        
     # 時間複雜度: O(1), 空間複雜度:O(1)  
    def push(self,value):
        if self.isFull():
            return 'The stack is full.....'
        else:
            self.top+=1
            self.list[self.top]=value
        
     # 時間複雜度: O(1), 空間複雜度:O(1)  
    def pop(self):
        if self.isEmpty():
            return 'Your stack is empty'
        else:
            popped_value=self.list.pop(self.top)
            self.top-=1
            return popped_value

    # 時間複雜度: O(1), 空間複雜度:O(1) 
    def peek(self):
        if self.list==[]:
            return 'Your stack is empty'
        else:
            return self.list[self.top]
    
    # 時間複雜度: O(1), 空間複雜度:O(1)    
    def deleteall(self):
        self.list=[]
        return 'All the elements in the stack got successfully removed'
    
    # 時間複雜度: O(1), 空間複雜度:O(1)
    def isEmpty(self):
        if self.top==-1:
            return True
        else:
            return False
customStack=stack(4)
customStack.isEmpty()
>>True
customStack.push(1)
customStack.push(2)
customStack.push(3)
customStack.push(4)
print(customStack.isFull())
>>True
print(customStack)
>>4
  3
  2
  1
customStack.peek()
>> 4
customStack.pop()
customStack.pop()
customStack.pop()
customStack.pop()
customStack.isEmpty()
>> True

用linked list做stack
linked list的部分,我感覺有圖可能比較好理解:
https://ithelp.ithome.com.tw/upload/images/20230918/20162172uppi6f1J9l.png

class Node:
    def __init__(self,value=None):
        self.value=value
        self.next=None

class Stack:
     # 時間複雜度: O(1), 空間複雜度:O(1)
    def __init__(self):
        self.head=None

     # 時間複雜度: O(N), 空間複雜度:O(1)
    def __str__(self):
        temp_node=self.head
        demo=''
        while temp_node:
            demo+=str(temp_node.value)
            demo+='\n'
            temp_node=temp_node.next
        return demo
    
     # 時間複雜度: O(1), 空間複雜度:O(1)
    def isEmpty(self):
        if self.head==None:
            return True
        else:
            return False
        
    # 時間複雜度: O(1), 空間複雜度:O(1)
    def push(self,value):
        new_node=Node(value)
        if self.isEmpty():
            self.head=new_node
        else:
            new_node.next=self.head
            self.head=new_node
        return 'Successfully push the value'
    
     # 時間複雜度: O(1), 空間複雜度:O(1)
    def pop(self):
        if self.isEmpty():
            return 'The stack is empty'
        else:
            popped_value=self.head.value
            self.head=self.head.next
            return popped_value
        
     # 時間複雜度: O(1), 空間複雜度:O(1)
    def delete(self):
        self.head=None       
exaStack=Stack()
exaStack.isEmpty()
exaStack.push(10)
exaStack.push(20)
exaStack.push(50)
exaStack.push(80)
exaStack.push(100)
print(exaStack)
>> 100
   80
   50
   20
   10
exaStack.pop()
>> 100
print(exaStack)
>> 80
   50
   20
   10

參考資料:
本文主要為udemy課程: The Complete Data Structures and Algorithms Course in Python的學習筆記,有興趣的人可以自己上去看看。


上一篇
Linked List - Doubly Linked List (雙向鏈結串列)
下一篇
Queue (佇列)
系列文
用python學習資料結構與演算法 學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言