Skip to content

Commit 6754f8c

Browse files
committed
🐛 Fix solution of 10.1-2
1 parent b5c944d commit 6754f8c

File tree

2 files changed

+30
-17
lines changed

2 files changed

+30
-17
lines changed

.gitignore

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Created by .ignore support plugin (hsz.mobi)
2+
.idea/uiDesigner.xml
3+
.idea/workspace.xml
4+
out/

src/C10/code/s10.1-2.kt

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
package C10.code
2+
23
/**
34
* 10.1-2
45
*
@@ -11,42 +12,46 @@ enum class Position{
1112

1213
class Stack(val capacity : Int = 10){
1314
val values = IntArray(capacity + 2)
14-
var left_top = 0
15-
var right_top = capacity + 1
1615

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
1822

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]
2026

2127
fun push(pos : Position, value : Int){
2228
if(full()){
2329
throw IndexOutOfBoundsException("overflow")
2430
}else{
2531
if(pos == Position.LEFT)
26-
values[++ left_top] = value
32+
values[++ values[0]] = value
2733
else
28-
values[-- right_top] = value
34+
values[-- values[capacity + 1]] = value
2935
}
3036
}
3137

3238
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] --]
3544
}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] ++]
4349
}
4450
}
4551
}
4652

4753
fun main(args: Array<String>) {
4854
val stack = Stack(5)
49-
//println(stack.C10.code.pop(C10.code.Position.LEFT))
5055
stack.push(Position.LEFT, 1)
5156
stack.push(Position.RIGHT, 2)
5257
stack.push(Position.RIGHT, 3)
@@ -55,6 +60,10 @@ fun main(args: Array<String>) {
5560
stack.push(Position.LEFT, 4)
5661
stack.push(Position.LEFT, 5)
5762
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)
5968
}
6069

0 commit comments

Comments
 (0)