I am trying to sort a stack such that the smallest elements are on the top of the stack using recursion. When I run the code, the result is sometimes unpredictable.
Here is the code
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())
In your recursive case, it looks like you're pushing the temp value twice, instead of the value you're actually trying to add. You have
else:
temp = self.sorted_stack.pop()
self.push(temp)
self.sorted_stack.push(temp)
but I think you want
else:
temp = self.sorted_stack.pop()
self.push(val)
self.sorted_stack.push(temp)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.