Python实现线性数据结构-线性表、栈、队列

线性数据结构:数据项之间具有一对一的线性关系,除了第一个和最后一个数据项之外,每个数据项都有且仅有一个前驱和一个后继。

复制代码
1.线性表:由有穷个元素组成,由一块连续内存顺序地存储在表中的元素。 也称为顺序表或连续表。可增删改查
2.栈:有序集合LIFO(后进先出)结构。添加、移除新项在顶部。 创建、添加、删除、判断是否为空、返回栈item数量
3.队列:有序集合FIFO(先进先出)结构。队尾添加,队首移除,。 创建、添加、删除、判断是否为空、返回栈item数量
python 复制代码
from collections import deque

def linear_list():
    # Python的内置列表(list)本质上就是一个线性表
    list = [1,2,3,4,5]
    print(list[0])
    list.append(6)
    list.remove(3)
    list[1] = 10
    print(list)

linear_list()



class Stack:
    # Python没有内置的栈,使用列表实现效果
    def __init__(self):
        self.items = []

    def is_empty(self):
        # 长度=0返回True, 否则返回false
        return len(self.items) == 0
    def push(self,item):
        self.items.append(item)

    def pop(self):
        if not self.is_empty():
            # pop() 移除并返回最后一个元素
            return self.items.pop()
        else:
            raise IndexError('pop from empty stack')

    def peek(self):
        if not self.is_empty():
            # 访问最后一个元素
            return self.items[-1]
        else:
            raise IndexError('peek from empty stack')

    def size(self):
        return len(self.items)

stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.is_empty())
print(stack.pop())
print(stack.peek())


class Queue:
    # Python collections.deque是一个双端队列
    def __init__(self):
        self.items = deque()

    def is_empty(self):
        # 长度=0返回True, 否则返回false
        return len(self.items) == 0

    def enqueue(self,item):
        self.items.append(item)

    def dequeue(self):
        if not self.is_empty():
            # pop() 移除并返回队首元素
            return self.items.popleft()
        else:
            raise IndexError('dequeue from empty queue')

    def size(self):
        return len(self.items)

queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue.is_empty())
print(queue.dequeue())
print(queue.size())

执行结果:

1

1, 10, 4, 5, 6

False

3

2

False

1

2

相关推荐
用户83562907805112 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
用户83562907805112 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
你好潘先生20 小时前
别再记命令了,用 yeero do 说句人话就能跑脚本,而且不烧 token
服务器·python·命令行
Agent_大师20 小时前
WebSocket 行情重连成功,K线缺口不会自动消失
python
荣码20 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
copyer_xyf20 小时前
FastAPI 如何连接 MySQL
后端·python
apocelipes1 天前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
用户8356290780511 天前
使用 Python 在 PDF 中创建与管理书签
后端·python
MeixianAgent2 天前
Python 回测数据入口怎么验?历史 K 线入库前先做 5 个检查
后端·python
咕白m6252 天前
用 Python 实现一键批量查找与替换 Excel 数据
后端·python