package datastructure.stack
import java.util.Scanner
import scala.reflect.ClassTag
import scala.util.control.Breaks
class ArrayStack[T: ClassTag]() {
private var maxSize: Int = _
private var top: Int = -1
private var stack: Array[T] = _
def this(maxSize: Int) = {
this()
this.maxSize = maxSize
this.stack = new Array[T](maxSize)
}
def getMaxSize: Int = this.maxSize
def ifFull: Boolean = top == maxSize-1
def isEmpty: Boolean = top == -1
def push(value: T):Unit = {
if (ifFull) {
println("栈满")
return
}
top += 1
stack(top) = value
}
def pop(): T = {
if(isEmpty){
throw new RuntimeException("stack is empty")
}
val value = stack(top)
top -= 1
value
}
def peek(): T = stack(top)
def show(): Unit = {
if(isEmpty){
println("栈空,没有数据")
return
}
for( i <- top to 0 by -1){
println(s"stack($i)=${stack(i)}")
}
}
}
object ArrayStack{
def apply[T: ClassTag](maxSize: Int): ArrayStack[T] = new ArrayStack(maxSize)
}
object Demo{
def main(args: Array[String]): Unit = {
val stack = ArrayStack[Int](4)
var key = ""
var loop = true
val sc = new Scanner(System.in)
while (loop){
println("show:显示栈")
println("pop:取出栈顶元素")
println("push:添加数据到栈")
key = sc.next()
key match {
case "show" =>
stack.show()
case "push" =>
println("输入一个整数")
val value = sc.nextInt()
stack.push(value)
case "pop" =>
try {
val i = stack.pop()
println(s"出栈数据为:$i")
} catch {
case e: Exception => println(e.getMessage)
}
case _ =>
sc.close()
loop = false
println("程序退出")
}
}
}
}
object Calculator{
def getPrio(oper: Char): Int ={
if(oper == '*' || oper == '/'){
1
} else if(oper == '+' || oper == '-'){
0
}else{
-1
}
}
def isOper(oper: Char) = {
oper == '*' || oper == '/' || oper == '+' || oper == '-'
}
def cal(num1:Int, num2: Int, oper: Char): Int = {
oper match {
case '+' => num1+num2
case '-' => num2-num1
case '*' => num1*num2
case '/' => num2/num1
}
}
def main(args: Array[String]): Unit = {
val exp = "30+2*60-2"
val numStack = ArrayStack[Int](10)
val operStack = ArrayStack[Char](10)
var index = 0
var num1 = 0
var num2 = 0
var oper:Char = ' '
var res = 0
var ch:Char = ' '
val ctrl = new Breaks
var keepNum = ""
ctrl.breakable(
while (true) {
ch = exp.substring(index,index+1).charAt(0)
if(isOper(ch)){
if(!operStack.isEmpty){
if (getPrio(ch) <= getPrio(operStack.peek())){
num1 = numStack.pop()
num2 = numStack.pop()
oper = operStack.pop()
res = cal(num1, num2, oper)
numStack.push(res)
operStack.push(ch)
}else{
operStack.push(ch)
}
}else{
operStack.push(ch)
}
}else{
keepNum += ch
if(index==exp.length-1){
numStack.push(keepNum.toInt)
}else{
if(isOper(exp.substring(index+1,index+2).charAt(0))){
numStack.push(keepNum.toInt)
keepNum=""
}
}
}
index += 1
if (index>=exp.length){
ctrl.break()
}
}
)
ctrl.breakable(
while (true){
if( operStack.isEmpty){
ctrl.break()
}
num1 = numStack.pop()
num2 = numStack.pop()
oper = operStack.pop()
res = cal(num1, num2, oper)
numStack.push(res)
}
)
println(s"表达式:$exp")
println(s"结果:${numStack.pop()}")
}
}