使用列表结构而不是列表方法的Python堆栈模拟

2024-04-25 05:50:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在不使用列表方法的情况下,如何模拟堆栈的push和pop函数?在

到目前为止,我有类似的东西,但我不确定这是否可行:

stack = []

def Push(stack, element):
    stack[len(stack)] = element

def Pop(stack):
    element = tos
    stack[len(stack) - 1] = None

    return element;

会推送工作,以这种方式动态地添加到列表中,len会适当地更新吗?在

对于pop,如何在不使用任何list函数的情况下从堆栈中“删除”?在


Tags: 方法函数none列表lenstack堆栈def
3条回答

您可以预先分配列表:

class Stack:
    def __init__(self, max_items):
        self.data = [0] * max_items
        self.max_items = max_items
        self.top = -1

    def push(self, i):
        self.top += 1
        if self.top < self.max_items:
            self.data[self.top] = i
        else:
            self.top -= 1
            raise ValueError("stack is full")

    def pop(self):
        if self.top >= 0:
            i = self.data[self.top]
            self.top -= 1
            return i
        else:
            raise ValueError("stack is empty")

    def __len__(self):
        return self.top + 1

您可以使用类似于的东西(警告:这是一个幼稚的实现-它不会对传递的参数执行检查)

class Stack(object):
    def __init__(self):
        self._stack = [] # Allocate an empty list

    def push(self, ele):
        self._stack += [ele] # Use list concatenation to emulate the `push` operation

    def pop(self):
        last = self._stack[-1:] # Return the last element of the list (also works for empty lists)
        self._stack = self.stack[0:-1] # Copy the elements from the beginning of the list to the last element of the list
        return last # return the last element

    # All stacks should have the `size` function to determine how many elements are
    # in the stack:
    def size(self):
        return len(self._stack)

    # Occasionally you'll want to see the contents of the stack, so we have to
    # implement the `__str__` magic method:
    def __str__(self):
        return '[%s]' % ','.join(map(str, self._stack))

注意:这个方法没有使用list方法作为append和{}。在

示例:

^{pr2}$

我想这个练习的目的是将堆栈看作一个abstract data type。你可以不使用列表来实现它们。如果你坚持使用列表,我不知道你说的“不使用列表方法”是什么意思。在

堆栈(作为列表)是一种具有两个构造函数的数据类型:(A)空堆栈,(b)将元素推送到堆栈上的结果。您可以在Python中实现这两种方法的许多不同实现。E、 g.,None可能是空堆栈,(x, s)可能是将x推到{}之上的结果。我建议你在寻求更多帮助之前,试着自己做一些类似的事情。在

相关问题 更多 >