• Python的栈和队列实现


    class Node:
        def __init__(self, data=None):
            self.next = None    
            self.data = data
    
    
    class Stack:
        def __init__(self):
            '''初始化'''
            self.top = None
            self.size = 0
    
        def push(self, data):
            '''将元素压入栈内'''
            node = Node(data)
            if self.top:
                node.next = self.top
                self.top = node
            else:
                self.top = node
            self.size += 1
    
        def pop(self):
            '''弹出栈顶元素'''
            if self.top:
                data = self.top.data
                self.size -= 1
                if self.top.next:
                    self.top = self.top.next
                else:
                    self.top = None
                return data
            else:
                return None
    
        def peek(self):
            '''查看栈顶元素'''
            if self.top:
                return self.top.data
            else:
                return None
    

    队列

    class Node:
        def __init__(self, data=None, next=None, prev=None):
            self.data = data
            self.next = next
            self.prev = prev
    
    class Queue:
        def __init__(self):
            self.head = None
            self.tail = None
            self.size = 0
    
        def enqueue(self, data):
            '''入队'''
            new_node = Node(data, None, None)
            if self.head is None:
                self.head = new_node
                self.tail = self.head
            else:
                new_node.prev = self.tail
                self.tail.next = new_node
                self.tail = new_node
            self.size += 1
    
        def dequeue(self):
            '''出队'''
            current = self.head
            if self.size == 1:
                self.size -= 1
                self.head = None
                self.tail = None
            elif self.size > 1:
                self.head = self.head.next
                self.head.prev = None
                self.size -= 1
    
        def iter(self):
            '''遍历队列'''
            current = self.head
            while current:
                data = current.data
                current = current.next
                yield data
    
  • 相关阅读:
    [转]如何从无到有建立推荐系统
    sql语句查询重复值
    推荐系统开发中十个关键点整理
    mongodb中的副本集搭建实践
    Unicode对象
    5W1H
    Python中实现switch分支结构
    数据结构-跳跃表
    redis入门笔记(3)
    redis入门笔记(2)
  • 原文地址:https://www.cnblogs.com/MartinLwx/p/9630293.html
Copyright © 2020-2023  润新知