Python 实现双链表,栈,队列

1.双链表

class Node(object):
    def __init__(self, value=None):
        self._prev = None
        self.data = value
        self._next = None

    def __str__(self):
        return "Node(%s)"%self.data


class DoubleLinkedList(object):
    def __init__(self):
        self._head = Node()

    def insert(self, value):
        element = Node(value)
        element._next = self._head
        self._head._prev = element
        self._head = element

    def search(self, value):
        if not self._head._next:
            raise ValueError("the linked list is empty")
        temp = self._head
        while temp.data != value:
            temp = temp._next
        return temp

    def delete(self, value):
        element = self.search(value)
        if not element:
            raise ValueError('delete error: the value not found')
        element._prev._next = element._next
        element._next._prev = element._prev
        return element.data

    def __str__(self):
        values = []
        temp = self._head
        while temp and temp.data:
            values.append(temp.data)
            temp = temp._next
        return "DoubleLinkedList(%s)"%values
2. 栈

class Stack(object):
    def __init__(self):
        self._top = 0
        self._stack = []

    def put(self, data):
        self._stack.insert(self._top, data)
        self._top += 1

    def pop(self):
        if self.isEmpty():
            raise ValueError('stack 为空')
        self._top -= 1
        data = self._stack[self._top]

        return data

    def isEmpty(self):
        if self._top == 0:
            return True
        else:
            return False

    def __str__(self):
        return "Stack(%s)"%self._stack

3.队列

class Queue(object):
    def __init__(self, max_size=float('inf')):
        self._max_size = max_size
        self._top = 0
        self._tail = 0
        self._queue = []

    def put(self, value):
        if self.isFull():
            raise ValueError("the queue is full")
        self._queue.insert(self._tail, value)
        self._tail += 1

    def pop(self):
        if self.isEmpty():
            raise ValueError("the queue is empty")
        data = self._queue.pop(self._top)
        self._top += 1
        return data

    def isEmpty(self):
        if self._top == self._tail:
            return True
        else:
            return False

    def isFull(self):
        if self._tail == self._max_size:
            return True
        else:
            return False

    def __str__(self):
        return "Queue(%s)"%self._queue



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值