1
1
package C10.code
2
+
2
3
/* *
3
4
* 10.1-2
4
5
*
@@ -11,42 +12,46 @@ enum class Position{
11
12
12
13
class Stack (val capacity : Int = 10 ){
13
14
val values = IntArray (capacity + 2 )
14
- var left_top = 0
15
- var right_top = capacity + 1
16
15
17
- fun empty () : Boolean = left_top == 0 && right_top == capacity + 1
16
+ init {
17
+ values[0 ] = 0
18
+ values[capacity + 1 ] = capacity + 1
19
+ }
20
+
21
+ fun emptyLeft () : Boolean = values[0 ] == 0
18
22
19
- fun full () : Boolean = left_top + 1 == right_top
23
+ fun emptyRight () : Boolean = values[capacity + 1 ] == capacity + 1
24
+
25
+ fun full () : Boolean = values[0 ] + 1 == values[capacity + 1 ]
20
26
21
27
fun push (pos : Position , value : Int ){
22
28
if (full()){
23
29
throw IndexOutOfBoundsException (" overflow" )
24
30
}else {
25
31
if (pos == Position .LEFT )
26
- values[++ left_top ] = value
32
+ values[++ values[ 0 ] ] = value
27
33
else
28
- values[-- right_top ] = value
34
+ values[-- values[capacity + 1 ] ] = value
29
35
}
30
36
}
31
37
32
38
fun pop (pos : Position ) : Int {
33
- if (empty()){
34
- throw IndexOutOfBoundsException (" underflow" )
39
+ return if (pos == Position .LEFT ){
40
+ if (emptyLeft())
41
+ throw IndexOutOfBoundsException (" underflow" )
42
+ else
43
+ values[values[0 ] -- ]
35
44
}else {
36
- if (pos == Position .LEFT ){
37
- left_top --
38
- return values[left_top + 1 ]
39
- }else {
40
- right_top ++
41
- return values[right_top - 1 ]
42
- }
45
+ if (emptyRight())
46
+ throw IndexOutOfBoundsException (" underflow" )
47
+ else
48
+ values[values[capacity + 1 ] ++ ]
43
49
}
44
50
}
45
51
}
46
52
47
53
fun main (args : Array <String >) {
48
54
val stack = Stack (5 )
49
- // println(stack.C10.code.pop(C10.code.Position.LEFT))
50
55
stack.push(Position .LEFT , 1 )
51
56
stack.push(Position .RIGHT , 2 )
52
57
stack.push(Position .RIGHT , 3 )
@@ -55,6 +60,10 @@ fun main(args: Array<String>) {
55
60
stack.push(Position .LEFT , 4 )
56
61
stack.push(Position .LEFT , 5 )
57
62
stack.push(Position .LEFT , 6 )
58
- stack.push(Position .RIGHT , 7 )
63
+ print (stack.full())
64
+ stack.pop(Position .LEFT )
65
+ stack.pop(Position .LEFT )
66
+ stack.pop(Position .LEFT )
67
+ stack.pop(Position .LEFT )
59
68
}
60
69
0 commit comments