Stacks and Queues in Python

3566 ワード


出典:PyNote

Stack


Stackは、「第1入力」(LIFO)の原則に従う.
  • push() : Insert the element at the top of the stack
  • pop() : Remove the topmost element of the stack
  • peek() : Return to the topmost element of the stack
  • isEmpty() : Return whether the stack is empty
  • size() : Return the size of the stack
  • Code

    class Stack():
        
        def __init__(self):
        	self.items = []
    
        def push(self, item):
            self.items.append(item)
        
        def pop(self):
            return self.items.pop()
        
        def peek(self):
            return self.items[-1]
                
        def isEmpty(self):
            return self.items == []
        
        def size(self):
            return len(self.items)       

    Queue


    Queueは、第1入力(FIFO)の原則に従う.
  • Enqueue() : Add an element to the end of the queue
  • Dequeue() : Remove an element from the front of the queue
  • isEmpty() : Return whether the queue is empty
  • size() : Return the size of the queue
  • Code

    class Queue(object):
        
        def __init__(self):
            self.items = []
        
        def enqueue(self, item):
            self.items.insert(0, item)
            
        def dequeue(self):
            return self.items.pop()
        
        def isEmpty(self):
            return self.items == []
        
        def size(self):
            return len(self.items)

    Deque(Double-ended-queue)



    ソース:geeks forgeeks
  • addFront() : Insert the element at the front of the queue
  • addRear() : Insert the element at the rear of the queue
  • removeFront() : Remove an element from the front of the queue
  • removeRear() : Remove an element from the rear of the queue
  • isEmpty() : Return whether the queue is empty
  • size() : Return the size of the queue
  • Code

    class Deque(object):
        
        def __init__(self):
            self.items = []
            
        def addFront(self, item):
            self.items.append(item)
        
        def addRear(self, item):
            self.items.insert(0, item)
            
        def removeFront(self):
            return self.items.pop()
        
        def removeRear(self):
            return self.items.pop(0)
            
        def isEmpty(self):
            return self.items == []
        
        def size(self):
            return len(self.items)