File tree 1 file changed +37
-9
lines changed
1 file changed +37
-9
lines changed Original file line number Diff line number Diff line change 1
1
# Time: push: O(n), pop: O(1), top: O(1)
2
- # Space: O(1 )
2
+ # Space: O(n )
3
3
#
4
4
# Implement the following operations of a stack using queues.
5
5
#
@@ -41,24 +41,52 @@ def empty(self):
41
41
class Stack :
42
42
# initialize your data structure here.
43
43
def __init__ (self ):
44
- self .q = Queue ()
44
+ self .q_ = Queue ()
45
45
46
46
# @param x, an integer
47
47
# @return nothing
48
48
def push (self , x ):
49
- q = self .q
50
- q .push (x )
51
- for _ in xrange (q .size () - 1 ):
52
- q .push (q .pop ())
49
+ self .q_ .push (x )
50
+ for _ in xrange (self .q_ .size () - 1 ):
51
+ self .q_ .push (self .q_ .pop ())
53
52
54
53
# @return nothing
55
54
def pop (self ):
56
- self .q .pop ()
55
+ self .q_ .pop ()
57
56
58
57
# @return an integer
59
58
def top (self ):
60
- return self .q .peek ()
59
+ return self .q_ .peek ()
61
60
62
61
# @return an boolean
63
62
def empty (self ):
64
- return self .q .empty ()
63
+ return self .q_ .empty ()
64
+
65
+ # Time: push: O(1), pop: O(n), top: O(1)
66
+ # Space: O(n)
67
+ class Stack2 :
68
+ # initialize your data structure here.
69
+ def __init__ (self ):
70
+ self .q_ = Queue ()
71
+ self .top_ = None
72
+
73
+ # @param x, an integer
74
+ # @return nothing
75
+ def push (self , x ):
76
+ self .q_ .push (x )
77
+ self .top_ = x
78
+
79
+ # @return nothing
80
+ def pop (self ):
81
+ for _ in xrange (self .q_ .size () - 1 ):
82
+ self .top_ = self .q_ .pop ()
83
+ self .q_ .push (self .top_ )
84
+ self .q_ .pop ()
85
+
86
+ # @return an integer
87
+ def top (self ):
88
+ return self .top_
89
+
90
+ # @return an boolean
91
+ def empty (self ):
92
+ return self .q_ .empty ()
You can’t perform that action at this time.
0 commit comments