设计一个算法,将栈中的元素按照递增顺序排列,但是不允许使用额外的数据结构。
# 示例
# 输入:[5, 3, 8, 6, 2]
# 输出:[2, 3, 5, 6, 8]
def sort_stack(stack):
if not stack:
return
temp = stack.pop()
sort_stack(stack)
insert_in_order(stack, temp)
def insert_in_order(stack, temp):
if not stack or stack[-1] <= temp:
stack.append(temp)
else:
popped = stack.pop()
insert_in_order(stack, temp)
stack.append(popped)
# 调用示例
stack = [5, 3, 8, 6, 2]
sort_stack(stack)
print(stack) # 输出 [2, 3, 5, 6, 8]