AlgoDesign

Sort stack

1class Solution:
2    # maintaining sorted order of stack
3    def __init__(self):
4        self.stk = []
5    
6    def push(self, val):
7        if len(self.stk) == 0: 
8            self.stk.append(val)
9            return
10        
11        tmp = []
12        while self.stk[-1] < val: tmp.append(self.stk.pop())
13        self.stk.append(val)
14        while tmp: self.stk.append(tmp.pop())
15
16    def pop(self):
17        if len(self.stk) == 0: return None
18        return self.stk.pop()
19
20    def peek(self):
21        if len(self.stk) == 0: return None
22        return self.stk[-1]
23    
24    # sorting a stack using another temporary stack
25    def sort(self, stk):
26        tmpStk = []
27        while len(stk) > 0:
28            stkTop = stk.pop()
29            while len(tmpStk) > 0 and tmpStk[-1] > stkTop: stk.append(tmpStk.pop())
30            tmpStk.append(stkTop)
31        
32        while tmpStk: stk.append(tmpStk.pop())