按字母顺序合并两个队列



我正在尝试将两个队列(这两个队列假定已按字母顺序排序(合并到第三个队列中,并按字母顺序返回第三个队列。例如:

queue1 = ["a","d","x"]
queue2 = ["b","c","y","z"]
# the third queue should look like
queue3 = ["a","b","c","d","x","y","z"]

这是我的代码(我没有使用方法merge()(:

import string
from pythonds.basic.stack import Stack
class Stack1Queue:
Stackone = Stack()
Stackto = Stack()
def __init__(self):
self.items = []
def add(self, element):
self.items.append(element)
def remove(self):
if len(Stackto) == 0:
if len(Stackone) == 0:
return None
while not Stackone.isEmpty():
p = Stackone.pop()
Stackto.push(p)
return Stackto.pop()
def peek(self):
return self.items[len(self.items) - 1]
def isEmpty(self):
return self.items == []
def size(self):
return len(self.items)

class MergeQueue(Stack1Queue):
adict = dict(enumerate(string.ascii_lowercase))
Queuethr = Stack()
def merge(self, Stackone, Stackto):
while not Stackone.isEmpty() and Stackto.isEmpty():
for k, v in adict.items():
if Stackone.peek() == adict.get(v):
Queuethr.push(Stackone.peek())
else:
Queuethr.push(Stackto.peek())
print(dict(Queuethr))
return 1

基本上,我的第一个类Stack1Queue是实现两个堆栈来创建队列。无论如何,我只是想知道我的merge函数是否正确编写。当我尝试运行时:

s = Stack1Queue()
p = Stack1Queue()
q = MergeQueue()
s.add("z")
s.add("y")
s.add("d")
s.add("b")
s.add("a")
p.add("x")
p.add("d")
p.add("c")
print(q.merge(s, p))

它返回 0 作为大小q

连接并使用sorted

queue1 = ["a","d","x"]
queue2 = ["b","c","y","z"]
queue3 = sorted(queue1 + queue2)
['a', 'b', 'c', 'd', 'x', 'y', 'z']

最新更新