我正在尝试对堆栈进行排序,以便使用递归将最小的元素放在堆栈的顶部。当我运行代码时,结果有时是不可预测的。
这是代码
class stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def is_empty(self):
return self.items == []
def size(self):
return len(self.items)
class sort_the_stack:
def __init__(self):
self.sorted_stack = stack()
def sort_stack(self, new_stack):
for i in range(new_stack.size()):
self.push(new_stack.pop())
return self.sorted_stack
def push(self, val):
if self.sorted_stack.size() == 0:
self.sorted_stack.push(val)
else:
temp = self.sorted_stack.peek()
if val < temp:
self.sorted_stack.push(val)
else:
temp = self.sorted_stack.pop()
self.push(temp)
self.sorted_stack.push(temp)
def peek(self):
return self.sorted_stack.peek()
def pop(self):
return self.sorted_stack.pop()
new_stack = stack()
new_stack.push(10)
new_stack.push(2)
new_stack.push(1)
new_stack.push(8)
new_stack.push(10)
new_stack.push(10)
stack1 = sort_the_stack()
stack1.sort_stack(new_stack)
print(stack1.pop())
print(stack1.pop())
print(stack1.pop())
print(stack1.pop())
print(stack1.pop())
print(stack1.pop())
答案 0 :(得分:0)
在你的递归情况下,看起来你正在推动临时值两次,而不是你实际想要添加的值。
else:
temp = self.sorted_stack.pop()
self.push(temp)
self.sorted_stack.push(temp)
但我认为你想要
else:
temp = self.sorted_stack.pop()
self.push(val)
self.sorted_stack.push(temp)