Skip to content

Commit 777e44e

Browse files
sort stack
1 parent bb88a45 commit 777e44e

File tree

1 file changed

+77
-0
lines changed
  • Python/chapter03/3.5 - Sort Stack

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
#!/usr/bin/python3
2+
'''Queue via Stacks: Implement a MyQueue class
3+
which implements a queue using two stacks.'''
4+
import unittest
5+
6+
7+
class Stack:
8+
def __init__(self):
9+
self.stack = []
10+
11+
def pop(self):
12+
if self.isEmpty():
13+
print('No stack to pop')
14+
return
15+
16+
return self.stack.pop()
17+
18+
def isEmpty(self):
19+
return len(self.stack) == 0
20+
21+
def push(self, value):
22+
self.stack.append(value)
23+
24+
def peek(self):
25+
if self.isEmpty():
26+
print('No stack to peek')
27+
return
28+
return self.stack[-1]
29+
30+
def printStack(self):
31+
if self.isEmpty():
32+
print('No stack to peeek')
33+
return
34+
35+
print("Top of stack\n _ ")
36+
for x in self.stack[::-1]:
37+
print('|', x, '|')
38+
print('|', '_', '|')
39+
40+
def sort(self):
41+
r = Stack()
42+
while not self.isEmpty():
43+
temp = self.pop()
44+
print('Temp ->', temp)
45+
while not r.isEmpty() and r.peek() > temp:
46+
self.push(r.pop())
47+
r.push(temp)
48+
print('self stack', self.stack)
49+
print(r.stack, end='\n\n')
50+
51+
while not r.isEmpty():
52+
self.push(r.pop())
53+
54+
55+
class Test(unittest.TestCase):
56+
@classmethod
57+
def setUpClass(cls):
58+
pass
59+
60+
@classmethod
61+
def tearDownClass(cls):
62+
pass
63+
64+
def test1(self):
65+
arr = [2, 5, 7, 10, 3, 10, -1, -100]
66+
print(arr)
67+
q = Stack()
68+
for x in arr:
69+
q.push(x)
70+
71+
q.printStack()
72+
q.sort()
73+
q.printStack()
74+
75+
76+
if __name__ == '__main__':
77+
unittest.main()

0 commit comments

Comments
 (0)