File tree 2 files changed +68
-0
lines changed
2 files changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ function MinStack ( ) {
2
+ var stackData = [ ] ,
3
+ stackMin = [ ]
4
+
5
+ this . push = function ( newNum ) {
6
+ if ( stackMin . length === 0 || newNum < this . getMin ( ) ) {
7
+ stackMin . push ( newNum )
8
+ } else {
9
+ var newMin = this . getMin ( )
10
+ stackMin . push ( newMin )
11
+ }
12
+ stackData . push ( newNum )
13
+ }
14
+
15
+ this . pop = function ( ) {
16
+ if ( stackData . length === 0 ) {
17
+ throw new Error ( 'Your stack is empty.' )
18
+ }
19
+ stackMin . pop ( )
20
+ return stackData . pop ( )
21
+ }
22
+
23
+ this . getMin = function ( ) {
24
+ var len = stackMin . length
25
+ if ( len === 0 ) {
26
+ throw new Error ( 'Your stack is empty.' )
27
+ }
28
+ return stackMin [ len - 1 ]
29
+ }
30
+
31
+ this . top = function ( ) {
32
+ return stackData [ stackData . length - 1 ]
33
+ }
34
+ }
Original file line number Diff line number Diff line change
1
+ function Queue ( ) {
2
+ var stackPush = [ ] ,
3
+ stackPop = [ ]
4
+
5
+ this . push = function ( newNum ) {
6
+ stackPush . push ( newNum )
7
+ }
8
+
9
+ this . pop = function ( ) {
10
+ if ( stackPop . length === 0 && stackPush . length === 0 ) {
11
+ throw new Error ( 'Queue is empty!' )
12
+ } else if ( stackPop . length === 0 ) {
13
+ while ( stackPush . length !== 0 ) {
14
+ stackPop . push ( stackPush . pop ( ) )
15
+ }
16
+ }
17
+ return stackPop . pop ( )
18
+ }
19
+
20
+ this . peek = function ( ) {
21
+ if ( stackPop . length === 0 && stackPush . length === 0 ) {
22
+ throw new Error ( 'Queue is empty!' )
23
+ } else if ( stackPop . length === 0 ) {
24
+ while ( stackPush . length !== 0 ) {
25
+ stackPop . push ( stackPush . pop ( ) )
26
+ }
27
+ }
28
+ return stackPop [ stackPop . length - 1 ]
29
+ }
30
+
31
+ this . empty = function ( ) {
32
+ return stackPop . length === 0 && stackPush . length === 0
33
+ }
34
+ }
You can’t perform that action at this time.
0 commit comments