File tree Expand file tree Collapse file tree 1 file changed +66
-0
lines changed
Python/chapter03/3.2 - Stack Min Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Stack Min: How would you design a stack which, in addition to push and pop, has
3
+ a function min which returns the minimum element? Push, pop and min should all
4
+ operate in 0(1) time.
5
+ Hints:#27, #59, #78
6
+
7
+
8
+ """
9
+ class stack :
10
+ def __init__ (self ):
11
+ self .items = []
12
+
13
+ def push (self ,item ):
14
+ """
15
+ Add an item to the top of the stack.
16
+ """
17
+ self .items .append (item )
18
+
19
+ def pop_ (self ):
20
+ """
21
+ Remove the top item from the stack.
22
+ """
23
+
24
+ return self .items .pop ()
25
+
26
+
27
+ def peek (self ):
28
+ """
29
+ Return the top of the stack.
30
+ """
31
+ return self .items [len (self .items )- 1 ]
32
+
33
+ def isEmpty (self ):
34
+ """
35
+ Return true if and only if the stack is empty.
36
+ """
37
+ if self .items == None :
38
+ return True
39
+ return False
40
+
41
+ def print_stack (self ):
42
+ print (self .items )
43
+
44
+ def stackMin (self ):
45
+ arr = self .items
46
+ min = arr [0 ]
47
+ for i in range (len (arr )):
48
+ if min > arr [i ]:
49
+ min = arr [i ]
50
+
51
+ return min
52
+
53
+
54
+
55
+ st1 = stack ()
56
+ st1 .push (7 )
57
+ st1 .push (4 )
58
+ st1 .push (5 )
59
+ st1 .push (9 )
60
+ st1 .push (0 )
61
+ st1 .push (6 )
62
+ st1 .push (1 )
63
+ st1 .push (5 )
64
+ st1 .push (7 )
65
+ st1 .print_stack ()
66
+ print (st1 .stackMin ())
You can’t perform that action at this time.
0 commit comments