Stacks and queues (Python implementation)

 

 

Stack

Stack LASS (Object):
     "" " Stack " "" 
    DEF  the __init__ (Self): 
        self.items = [] 

    DEF is_empty (Self):
         "" " determines whether the air " "" 
        return self.items == [] 

    DEF the Push (Self, Item):
         "" " added element " "" 
        # plug the end LIFO 
        self.items.append (Item) 

    DEF pOP (Self):
         "" " pop elements " "" 
        # pop removed from the end of the list 
        return self.items.pop () 

    DEF PEEK (Self):
        "" " Return to the top element ." "" 
        Returnself.items [-. 1]   # Python listing properties 

    DEF size (Self):
         "" " return stack size " "" 
        return len (self.items)

queue

# Queue (queue): allows only the insertion end and at the other end of the linear table delete operation. 
FIFO
 "" " 

class Queue (Object): 
    " "" Queue "" " 
    DEF the __init __ (Self): 
        Self .__ List = [] 

    DEF is_empty (Self): 
        " "" whether the queue is empty "" " 
        return Self List == .__ [] 
    "" " implemented enqueue dequeue there are two ways, according to the use of the queue to determine what action to realize how frequently O (. 1) O (n-) " "" 
    DEF the enqueue (Self, Item) : 
        "", " into queue " "" 
        return Self .__ list.insert (0, Item) 

    DEF dequeue (Self): 
        "" " dequeues " ""

        
        return len(self.__list)

Deque

class Dueue():

    def __init__(self):
        self.__list = []

    def add_front(self, item):
        self.__list.insert(0,item)

    def add_rear(self, item):
        self.__list.append(item)

    def pop_front(self):
        return self.__list.pop(0)

    def pop_rear(self):
        return self.__list.pop()

    def is_empty(self):
        """判断队列是否为空"""
        return self.__list== [] 

    DEF size (Self):
         "" " return queue size " "" 
        return len (Self. __List )

 

Guess you like

Origin www.cnblogs.com/sometingintheway/p/11955957.html