Computer Science
Write a Python program to sort a Stack in ascending order without using an additional Stack.
Python
Python Stack
3 Likes
Answer
def pushSorted(s, num):
if len(s) == 0 or num > s[-1]:
s.append(num)
return
else:
t = s.pop()
pushSorted(s, num)
s.append(t)
def doSort(s):
if len(s) != 0:
t = s.pop()
doSort(s)
pushSorted(s, t)
s = []
s.append(12)
s.append(5)
s.append(-3)
s.append(4)
s.append(10)
print("Stack before sorting: ")
print(s)
doSort(s)
print("\nStack after sorting: ")
print(s)Output
Stack before sorting:
[12, 5, -3, 4, 10]
Stack after sorting:
[-3, 4, 5, 10, 12]
Answered By
3 Likes
Related Questions
Write AddClient(Client) and DeleteClient(Client) methods in Python to add a new client and delete a client from a list client name, considering them to act as insert and delete operations of the Queue data structure.
Write Addscore(Game) and Delscore(Game) methods in Python to add new Score in the list of score in a game and remove a score from a list of score of a game considering these methods to act as PUSH and POP operation of data structure Stack.
A Stack STK and Queue QUE is being maintained. Their maximum size is the same:
(i) check whether they have the same size, i.e., have the same number of elements.
(ii) check for equality of Stack and Queue, i.e.,
- Retrieve an element from the Stack and one element from the Queue.
- Compare the two.
- Stop and report if elements are different.
Write an algorithm to insert element into Stack as a list.