如何正确使用队列中的popLeft出列?

时间:2018-01-20 09:10:41

标签: python algorithm stack queue logic

git filter-branch

这是一项学校作业,我不允许修改函数入队和出队的代码以及def__init __(self)。 我正在尝试使用popleft作为从队列中将项目出列的手段。但是,当我使用popleft时,编译器返回整个队列而不是仅返回队列的第一个堆栈。话虽这么说,队列的大小减少了一个。对此有何解释?

编译器返回[['stone','atone'],['stone','shone'],['stone','scone']]当我只希望它返回['stone','弥补']。

1 个答案:

答案 0 :(得分:1)

就像上面的注释一样,您传递的是Stack对象,而不是堆栈中的元素。试试这个

import collections
class MyStack:
    def __init__(self):
        self._data = []

    def push(self, value):
        self._data.append(value)

    def size(self):
        #Return the number of elements in the stack
        return len(self._data)

    def toString(self):
        #Return a string representing the content of this stack
        return str(self._data)

class MyQueue:
    def __init__(self):
        self._data = collections.deque([])

    def enqueue(self, value):
        self._data.append(value)

    def dequeue(self):
        return self._data.popleft()

    def size(self):
        #return the number of elements in the queue
        return len(self._data)

queue1 = MyQueue()
dq = MyStack()
stack1 = MyStack()

stack1.push(['stone', 'atone'])
print "size of stack is now :" ,stack1.size()
queue1.enqueue(stack1.toString())
print "size of queue is now :", queue1.size()
print "size of stack is now :" ,stack1.size()
stack1.push(['stone', 'shone'])
stack1.push(['stone', 'scone'])

dq = queue1.dequeue() # i would like dq to be ['stone','atone']

print dq